Factorial query


#1



Hi, please could you help me out with the "factorial" problem - I have been trying to solve it on my own with no luck. I had a look at what others have done but it ends up confusing me when I do not think along their line of thought.

Thank you in advance for your help!

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


def factorial(x):
    if x == 1 or x == 0:
        return 1
    while x > 1:
        number_list = []
        factorial_answer = x * range(x-1, 0, 1)
        return factorial_answer


#2

the result needs to be a integer

here:

factorial_answer = x * range(x-1, 0, 1)

there are so many problems here. Why x-1? You want x to be included. If i want the factorial of 5 (5 * 4 * 3 * 2 * 1), 5 is most certainly included

you want to get from higher value (x) to lower value (0) with steps of +1, how does that work?

then another problem:

print [1,2,3] * 2

see how this simply multiplies each item in list with 2? That is what you are currently doing (range produces a list), not sure, don't think this will help you solve factorial, have you looked at the hint in exercise


#3

Hi stetim94

Thank you for the quick response.

Let me first explain my logic behind what I was trying to do. If we were to use the number "5" like in your example, in my mind the formula "x * range(x-1, 0, 1)" is meant to multiply 5 by 4 (which is the "x - 1" part) and continue doing so until it reaches 0. I do agree however that I should have used a step of "-1" and not "1" since we are moving down.

Why would using the "Range" function/formula not be correct?

Thank you again for your time.


#4

that is not going to happen

Either way, use a while loop or a for loop with range, not both

The easiest solution is to declare a variable total and give it a value of 1

then using for with range or while, loop over all the values and multiply them with total. Store the result of this multiplication in total so total will increase to get the factorial in the end)


#5

This works for me:

def factorial(x):
if x == 0 or x == 1:
return 1
else:
fact = x * factorial(x - 1)
return fact


#6

Thank you very much!

I cannot believe how much time I spent for 2 lines of code! But even with that answer - it makes no sense why it works?

Where is the loop? Shouldn't there be a loop so that Python knows to go back and multiply the "list" of numbers i.e. from 5 to 1 (5 x 4 x 3 x 2 x 1)? When I read the above line:

fact = x * factorial(x - 1)

what the answer seems like it would be is: 5 x (5 - 1) = 20 which is wrong. So how does this end up being correct - i.e. what is Python reading this as?


#7

its the recursive solution. I don't you should bother with understanding this, i think you would struggle too much with it, go back to the loops, we can make more and better progress there


#8

A post was split to a new topic: Factorial


#9

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