Factorial


#1



I am trying to wrap my head around where I am going wrong...

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

I am getting the error: 
 factorial(2) returned 1 instead of 2

When I change my code to this:

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

I receive this error:
 factorial(4) returned 12 instead of 24

Could someone please explain where I am going wrong and what to do to fix it?

Thanks


#2

the biggest problem is here:

answer = count * (x - 1)

you assign something to answer, which means each iteration of the loop answer gets re-assigned. Instead, you should define answer before the loop, give it a value of 1.

Then in the loop increase answer:

answer = answer * ??

#3

Hey stetim94,

Thanks for the advice, but i now get this:

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

Oops, try again. factorial(2) returned 1 instead of 2

Could you link me a full correct solution so i can see if i understand it?

Thanks!


#4

this code:

        count = x
        answer = 1
        while count >= 0:
            answer = answer * (x - 1)
            count -= 1
            if count == 0:
                return answer

can be so much more efficient. lets start by removing this line:

count = x

lets change the while condition, we want the loop to run while x is greater then zero:

while x > 0:

this way, we can just use x. Then we multiply answer by x (not x - 1) and store the result of this in answer

then we decrease x by one.

after the loop, return x

given the loop is now far more efficient in design, you can do this :slight_smile:


#5

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

I did it! I think that the line with the answer on it was definitely confusing me


#6

but do you understand now?

I would do the following:

answer = 1
while x > 0:
    answer = answer * x
    x -= 1
return answer

this way, answer is returned after your loop has finished running, now you can remove your if and elif which check for x equals zero and x equals one, since they are now redundant.


#7

A post was split to a new topic: Factorial


#8

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