Factorial


#1



Factorial


To the best of my understanding, this should work. I am at a loss.
It returns 20 as the answer to factorial(4) instead of 24.


def factorial(x):
    if x == 1:
        return 1
    else:    
        a = 0
        while x > 0:
            a = a + x * (x - 1)
            x -= 1
            if x == 0:
                return a
        
print factorial(4)


#2

There should be no adding in a factorial function. Review your process and see if you can adjust your method.


#4

I removed the 'a +". I am racking my brain to understand why it still does not work.
It now returns "0" as the answer


#5

I understand that I could solve this with a range function, but I feel committed to making it work this way and want to understand why it isn't working as is.


#6

What if you start with a = 1 before the loop?

a *= x

#7

I have tried those changes already without any luck. When I change the a = 1 before the loop, the result doesn't change. And inserting a *= x instead of a = x * (x-1) only makes the answer farther away from the intended answer.

def factorial(x):
if x == 1:
return 1
else:
a = 1
while x > 0:
a = x * (x - 1)
x =- 1
return a

print factorial(6)

With the line above, it seems that the problem is with the while loop not looping. The program only multiplies the first two factorials. factorial(6) is 30. factorial(4) is 20.


#8

This is not accumulating a net product on a, but writing the last product, only.

while x > 0:
    a *= x
    x -= 1

return a

If you look closely, we do not even have to test for 1. a is 1 and 1 * 1 is 1, so 1! is 1.

We do need to test for 0, though, since 0! is 1, also.

if x == 0: return 1

#9

I finally got it. Thank you so much!
The only part that i had not tried changing, and that finally made it work, was changing "=-" to "-=".
I am still very new to this, thanks for your patience


#10

You're welcome. No patience on my part, but on yours. Sticking with it takes patience, and lots of it. Keep it up!


#12