5 - factorial. can someone please help me :(


#1

my code doesnt seem to work but i cant find out why

def factorial(x):
    if x == 0:
        return 0
    elif x ==1:
        return 1
    else:
        sets = []
        count = x -1
        while count < x and count != 0:
            current = x * count
            sets.append(int(current))
            count -= 1
        return sum(sets)

it keep coming up with the error

 Oops, try again. factorial(3) returned 9 instead of 6

but i cant understand why ? can anyone please help me. Thanks in advance


#2

Hello, @atlantaspp!
The thing with factorial is that you're not adding numbers but multiplying them so even appending each of them into a list and get the sum if isn't right but seriously, you were really close!
Using the number three, as an example, you'll append the values 6 and 3 because you'll calculate:

#First execution:
#x = 3
#count = 2 (because x - 1 is 3 -1 which is 2)
#current = None (has no initial value)
sets = [] #Empty
while 2 < 3 and 2 != 0:
      current = 3 * 2 #Which is 6
      sets.append(int(current))
      count -= 1
#Second execution 
#x = 3
#count = 1 (because you decreased it's value by one)
#current = 6 (has no initial value)
#sets = [6]
while 1< 3 and 1 != 0:
      current = 3 * 1 #Which is 3
      sets.append(int(current))
      count -= 1
#Third execution 
#x = 3
#count = 0 (because you decreased it's value by one)
#current = 6 (has no initial value)
#sets = [6]
while  0 < 3 and 0 != 0:
      current = 3 * 1 #Which is 3
      sets.append(int(current))
      count -= 1
#After all of that, since the program evalueted the condition and it's 
#False, the execution will leave the for loop and go to the next
#instruction right after it which is the sum()
#It will add the values in your list sets which are 6 and 3, returnig 9

Try to check your code and see where you could actually alter to change it up.

Remeber: if I tell you to calculate me the factorial of 4, you're supposed to do 4*3*2*1 or 1*2*3*4 and bring back the result which is 12.

Hope I was clear, otherwise I'll find another way to explain it! :smiley:


#3

@g4be thanks for your help. I understand where i went wrong now thanks to your explanantion I manage to get it working now, don't know why i used a list in the first place . Thanks again for your help much appreciated .


#4

No problem, Pierrepp! Glad to help!


#5

@g4be Could you please help me? I dont know how to decrease my count even more to allow more numbers into my factorial:

def factorial(x):
    if x == 1 or x == 0:
        return 1
    y = 1
    while x > 1:
        y = y * x
        x = x - 1
        return y * x

#6

@youngbonaparte: Put your return outside your while loop and return the value in y, since that will get the final result.


#7

Thanks again @g4be will make sure my return is outside my loop next time!


#8

@youngbonaparte: No problem! Glad to help :slightly_smiling: