Understanding logic behind "factorial" problem


#1

I'm on exercise 1.5 of Practice Makes Perfect, called "factorial". Here is my code and corresponding understandings:

def factorial(x):
    factors = []
    while x>0:
        factors.append(x)
        x = x-1
        print factors

To get the factors of some number x, I created an empty list called factors and while x>0, I append a number to that list then subtract one and repeat. The list factors successfully prints all the factors of a number. I'm just stuck on how to now multiply them all together. My intuition is to add a for loop to iterate through all the numbers in my list and multiply them together, I'm just confused as to how to accomplish this?


#2

but appending to list and then looping over the list is a bit double, isn't it?

why not, instead of appending, multiply directly? You can simply make factors a integer (1), and multiply using the while loop you already have


#3

Hi, thanks for your prompt reply. I think I'm a little confused. The reason I thought to append to a list was to break the number x into the smaller numbers necessary to complete the multiplication. Can you explain how making factors into an integer would help?


#4

well, then you can multiply each number with factors to get the factorial

for example for x=4

you would loop over the numbers using while loop:

1 * 4 
4 * 3
12 * 2
24 * 1

the step of the loops broken down by multiply each number of the loop with factors, resulting in the factorial


#5

I'm not sure how I would accomplish what you're saying using a while loop:

def factorial(x):
    n = 1
    while x>0:

For x=4, how would you make it so each time the loop runs, it subtracts 1 from x while increasing n by the proper amount?


#6

these are two steps, first multiply n with x and store the result of this multiplication in n, then decrease x by 1, you already know how to do this, since you have done it:

x = x-1

#7

Ok, so this is my code now:

def factorial(x):
    n = 1
    while x > 0:
        n=n*x
        x -= 1

It does not seem to be storing the product of n*x in n properly. My end result is always 0, and when I throw a print function inside the while loop to diagnose, I can see that n is remaining to be stored as 1. I even tried placing the n=1 inside the while loop with no success. Any suggestions?


#8

your function now calculate the correct factorial:

def factorial(x):
    n = 1
    while x > 0:
        n=n*x
        x -= 1
    print n

factorial(5)

see? Works fine, now for the exercise your function should return the factorial


#9

Thank you stetim94, your help and patience was much appreciated.


#10

don't forget that function not execute unless called

No problem, you're welcome :slight_smile:


#11

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