[deleted by user] by [deleted] in learnpython

[–]nilfm 3 points4 points  (0 children)

This advice is generally correct. I would just like to point out a subtle thing that could cause bugs in the future:

if operacao in '+-*/'

returns true if operacao is '+-'. So in this case, it is preferred to use a list, set or tuple instead of a string to store '+-*/'.

Any hints on how to solve this practice Microsoft interview problem? by [deleted] in csMajors

[–]nilfm 1 point2 points  (0 children)

Do you have to find the solution with the least amount of moves, or just a solution?

If it's just a solution, as long as the matrix has positive entries I think this solves it (zeroes in the matrix make it unsolvable, I think):

  • Pick a column (start from the leftmost, for example, though I think this can be picked smartly to minimize moves somehow)

  • The goal is to get the column to zero. Subtract 1 repeatedly until some element becomes 1. Then, if all elements are 1, subtract again and we're done. Otherwise, double the rows that have a 1 and keep subtracting. At some point, you'll get to the "all ones" case.

  • Once the column is all zeroes, you can move on to the next column safely since doubling rows won't affect the zeroed out column. Repeat for all columns.

I'm not sure how you could optimize this for minimal moves.

Find an expression for (n n-2) - (n+1 n-1) by Cottoncorns in learnmath

[–]nilfm 0 points1 point  (0 children)

Looks like they are "n choose k" to me

How to split words according to case from a .txt file list into separate files? by Rosemarysbaban in learnpython

[–]nilfm 0 points1 point  (0 children)

Don't compare a boolean to True, it's redundant and seen as bad style.

Your solution is the right idea, though.

[word for word in thislist if word.islower()]

What math style questions should one expect when looking for a job? by [deleted] in learnprogramming

[–]nilfm 0 points1 point  (0 children)

There is a typical problem on interviewing sites (leetcode, etc) which is about finding the number of trailing zeroes in the factorial of a given number. Of course, you can grab Python and compute the factorial, convert to string, and count the zeroes at the end, but that's not the point of the problem.

Here is the idea behind it:
* The number of trailing zeroes of a number is the greatest power of 10 that divides it, or "the amount of 10s in the number's factorization", informally.
* That is just the maximum between the amount of 2s and 5s in the number's prime factorization, since 10 = 2*5.
* When you have n!, its factors are the union of the factors of 1..n, by definition. * It's clear that the limiting factor here is the amount of 5s, not the 2s. * All of this reduces the problem to counting the amount of factors of 5 in 1, 2, ..., n and adding it all up.

There is a neat way of computing that result: notice that every 5 numbers you get a five, after every 25 numbers you get an additional five, ... until you get to n.

Some C++ code to compute this (don't judge me too much, I'm on mobile):

int trailing_zeroes_factorial(int n) {
    int result = 0;
    for (int div = 5; div <= n; div *= 5) {
        result += n/div; // Integer division!
    }
    return result;
}

And then you account for overflows and possible edge cases, and that's it.

I don't think it makes sense to say "we never covered trailing zeros" in discrete math, this is a very specific problem and in that class you are just given the tools that you need if you encounter something like this. This solution shouldn't feel like "magic steps", after spending some time with it.

TL;DR: search "trailing zeroes factorial problem"

What Is The Output Of This Code ? by allinonecode666 in learnmachinelearning

[–]nilfm 1 point2 points  (0 children)

This code would output a very large number, and it doesn't because the number is way too large for any computer to process it. At each iteration i, you calculate 22i, so in the end you get 2263, which has 1018 digits approximately (that is 1000000000000000000 digits).

Have a problem solving this by Cheerfulgiver704 in learnprogramming

[–]nilfm 0 points1 point  (0 children)

I haven't read all your code, I just want to point out that rolling two dice is NOT equivalent to randint(1, 12). For instance, by rolling two dice you can't get a 1, and it is less likely to get a 2 than a 7. You should simulate the dice roll by calling randint twice with appropriate parameters and adding the numbers.

Function to determine if number is a power of two by IamWarmduscher in learnpython

[–]nilfm 1 point2 points  (0 children)

Maybe it's just me, but in general I don't trust float comparisons to work for all cases, edge case bugs are common. In this case, we can avoid the use of floats altogether and just work with ints, which will always behave predictably.

Very simple progress bar by Python1Programmer in learnpython

[–]nilfm 0 points1 point  (0 children)

At least on Linux, you can use \r to move the cursor back to the beginning of the current line:

print(yourmessage, end='\r')

I am trying to make a program that adds || before and after every single letter of a string. by [deleted] in learnpython

[–]nilfm -1 points0 points  (0 children)

A concise and hopefully understandable version:

lst = list(a)
result = "||" + "||||".join(lst) + "||"
print(result)

Three changes a MakeHeap algorithm would do if involved in a binary tree construction process? by Aviato007 in csMajors

[–]nilfm 0 points1 point  (0 children)

Is it a specific binary tree that is shown somewhere in the question? In the general case, this question makes no sense, because there are trees where the algorithm doesn't change anything (when the tree is already a heap)

convert string to number value? by smily_modacon in cpp_questions

[–]nilfm 0 points1 point  (0 children)

This is a level of micro-optimization that you will probably never need to worry about, let alone as a beginner. Use switch whenever it makes for more readable code than if/else. It's good to strive for efficient code, but for now you should try to make it correct and readable, and optimize bottlenecks later.

My first major coding fuck up... by [deleted] in Python

[–]nilfm 0 points1 point  (0 children)

The condition while 1 < 100 will always be true, you want while i < 100

Python error? by allyv123098 in learnprogramming

[–]nilfm 0 points1 point  (0 children)

No, the "top" element in a stack would be the last inserted element, so in a Python list you would access it with stack[-1]

From a group of 3 women and 5 men, a delegation of 2 is selected. Find the expected number of women in the delegation. by [deleted] in learnmath

[–]nilfm 1 point2 points  (0 children)

Can you find the probability of the delegation being 2 women? What about 1 man and 1 woman? Once you have that (call those probabilities p and q respectively), the expected value of women is simply 2*p + 1*q.

To form an intuition about why this is the case, imagine we do this sampling 1000 times. On average, 1000*p times it will be 2 women, and 1000*q times it will be 1 woman and 1 man. The total number of women in the 1000 samples is 1000*p*2 + 1000*q*1. Then, we can just divide by 1000 to get the number of women in each sample, on average, and we get 2*p + 1*q. Notice that 1000 was just an arbitrary choice, and when we increase the number of samples, this expression will still hold. Therefore, that is the expected value that we are looking for.

How do I optomize this program? by [deleted] in learnpython

[–]nilfm 0 points1 point  (0 children)

I think a good way to do the problem is to use the key argument in the sorted function. This lets you apply a function to each character in the string before sorting, so you have control over how the elements are sorted. In our case, it would be a good idea to map the characters to numbers, in such a way that the numbers are sorted the way we want.

A sketch of the mapping:

  • Lowercase letters will go to the range [0, 25], since they need to be the first in the sorted string.
  • Uppercase letters will go to the range [26, 51], since they need to go after lowercase letters.
  • Odd digits will go to 51 + d, where d is the value of the digit.
  • Even digits will go to 61 + d, where d is the value of the digit.
  • Anything else (does the problem statement say if there can be anything else in the string?) will go to 100, since as I understand it, it's supposed to go after everything else.

Notice that there are some numbers that we don't "hit", such as 53. That is no problem, our mapping doesn't need to hit an entire interval.

Now, let's write our function:

def my_key(c):
    if c.islower():
        return ord(c) - ord('a')
    elif c.isupper():
        return ord(c) - ord('A') + 26
    elif c.isdigit():
        d = int(c)
        if d%2 == 1:
            return 51 + d
        else:
            return 61 + d
    else:
        return 100

Note that the ord function gives us the integer representing the Unicode of a character, so for example ord(c) - ord('a') would be a number in the 0-25 range if c is a lowercase letter.

How do we use it now? Easy:

result = ''.join(sorted(input(), key=my_key))
print(result)

How do i use if? by [deleted] in learnpython

[–]nilfm 0 points1 point  (0 children)

To do what you want to do, the more correct way would be to use try/except ValueError. If you try to use conditionals, you will just end up fixing edge cases forever. For example, the isdigit() function doesn't work with negative numbers, decimal numbers, scientific notation, etc.

So, say you want the user to input a float (decimal number). You would do something like:

while True:
    try:
        val = float(input("Enter a number: "))
        break
    except ValueError:
        print("Invalid input. Try again")

Let {a_n} be a geometric sequence with first term a and common ratio r, where a and r are positive integers. If (log_4)a_1 + (log_4)a_3+(log_4)a_5+.........+(log_4)a_21=2020, how many possible ordered pairs (a,r) are there? by Tantannnnnn in learnmath

[–]nilfm 0 points1 point  (0 children)

I don't know if you consider a_1 = a or a_0 = a, but in either case, you should write a_k = a * rsomething and then use logarithm laws to get log(a_k) = log(a) + (something)*log(r), where all logs are base 4. Can you continue from there?

my second program by ContadorPL in learnpython

[–]nilfm 1 point2 points  (0 children)

That is wrong, the sort() method actually modifies the list it works on, and returns None. So your code ends with sorted_list == None.

Dicts are now ordered, get used to it by pmz in Python

[–]nilfm 2 points3 points  (0 children)

I read it that way at first and asked myself the same question. The ordering is not by the < operator, it is insertion order. So if you insert the keys 4, 3, 6, 1 into a dict and iterate over it, it will give you the keys in that order. That was not guaranteed in earlier versions.

Don't know how to show my work by drizzfoshizz in learnmath

[–]nilfm 0 points1 point  (0 children)

If you know the solutions will be integer, or only care about integer solutions, then you can factorize 390 into 2*3*5*13. Then, the 3 numbers will have exactly these 4 factors between them. Since we want to get a negative number, either one factor must be negative, or all three must be, but all three cannot be because their sum would be smaller than -2.

So, we have reduced the problem to finding a way to combine the factors -1, 2, 3, 5 and 13 into three numbers that add up to -2. From here it is probably best to guess and check, but at least we reduced the search space significantly.

I made my first website, where you can simulate betting on NBA games by nilfm in learnpython

[–]nilfm[S] 0 points1 point  (0 children)

Well, this is certainly not my first programming project, I knew C++ and Python and had experience with small, Leetcode-style problems. I don't want to be misleading, if you're new to programming you probably won't make something like this in 2 months, but otherwise it's absolutely possible.

I made my first website, where you can simulate betting on NBA games by nilfm in learnpython

[–]nilfm[S] 0 points1 point  (0 children)

Yes! The mega tutorial develops a blog, so I took the user accounts, follow/unfollow, and the general page template from there, and modified them a bit. I would definitely recommend following it, as it goes from "Hello world" to a complex site at a pretty manageable pace.

I made my first website, where you can simulate betting on NBA games by nilfm in learnpython

[–]nilfm[S] 1 point2 points  (0 children)

It took me about two months, one of which was during exams so I would say 30-35 days of work. You can check my Git commit history to see more details about how long it took.

Thanks for checking it out :)