#5 Factorial & #6 Prime- How do you know if your solution is the best solution?


One thing I struggle with when going through these exercises is knowing why one solution is better than another. I've heard that if you can accomplish something with a smaller amount of code, then that's a good sign, but how do I know when a for loop is better than a while, or when I should use nested if statements? Do I need to be mindful of performance differences between different approaches?

Below are my solutions for #5 Factorial and #6 Prime. What changes are some changes I could make to improve them and what would be the justifications for those changes?

#5 Factorial

def factorial(x):
    if int(x) > 0:
        fact = 1
        for x in range(0,x):
            fact *= (x + 1)
        return fact

#6 Prime

def is_prime(x):
    fact = 0
    for n in range(1,x+1):
        if x % n == 0:
            fact += 1
    if fact == 2:
        return True
        return False


We are a long ways from worrying which is the best solution. Better that we try them all, and be able to understand and explain each one. It is also more important that the programs work as expected. Does your is_prime function work as expected?


Yes, both my functions are working as expected, I was just thinking it'd be good to learn some best practices so that I could start out trying to apply the best solution.


Something of a best solution may exist, but this is not the time to be seeking it. Try everything at hand and learn the in's and out's of each new approach. The mechanics and syntax are what we are focused upon, here. It's utopian ideology to think there is such a thing as a best way. There is not, just many good ways (the ones that work as expected).


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.