Factorial trouble


#1



So this returns 12 for factorial(4) instead of 24, which indicates it is not looping, but instead just multiplying by x-a once, but I cannot understand why.


def factorial(x):
    for a in range(1, x):
        result = 0
        result += x*(x-a)
        return result
    if x <= 1:
        return 1
        
print factorial(4)


#2

Set this outside of the loop. Is a for loop with a range the way to go? Have you tried while?

product = 1
while x > 1:
    product *= x
    x -= 1
return product

That aside, let's look a little more closely at your code:

The if statement could go first.

    if x < 2:
        if  x > -1: return 1
        else: raise ValueError

    result = 1
    for a in range(2, x + 1):
        result *= a
    return result

#3

Setting the result outside the loop doesn't seem to solve the problem. Nor does putting the if statement first. I tried a while loop but couldn't get it to work either. Can it work with this for loop or am I barking up the wrong tree?


#4

Show us your code, again, please. And post a link to this exercise so we can test it. Thanks.

You do see where the return is in your original loop, right? It should be four spaces to the left.


#5

Yup sorry, here's the link - https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096

Here's the code, I changed it a little:

def factorial(x):
    if x <= 1:
             return 1
    result = 0
    for a in range(1, x):
        c = x - a
        result += x*c
        return result
    
        
print factorial(5)

#6

The return statement still has too much indentation.

let x = 7

x * 6  =>  6x
x * 5  =>  5x
x * 4  =>  4x
x * 3  =>  3x
x * 2  =>  2x
x * 1  =>   x
          21x

is 21 * 7 equal to 7!? There is the flaw in your algorithm.

   7 * 6 => 42
  42 * 5 => 210
 210 * 4 => 840
 840 * 3 => 2520
2520 * 2 => 5040
5040 * 1 =======> 5040

Off topic, but only slightly,,,

To get a good picture of where factorials are used, combinatronics is one where is it is woven into the mathematics.

Consider this problem...

Given 10 colored marbles, all unique, how many combinations taking 3 at a time can be chosen? The three are put back in each time so there are always 10 marbles..

I'll leave this with you.

You can test your factorial function with this program:

def combo(n,r):
    n_f = factorial(n)
    r_f = factorial(r)
    nrf = factorial(n-r)

    nCr = int(n_f / (r_f * nrf))

    print ("{0} choose {1} = {2}".format(n, r, nCr))

combo(10,3)

combo(49,6)

If you get the following output, your program works correctly, at least at this point. There are lots of ways to foul a program as you will discover in your travails.

10 choose 3 = 120
49 choose 6 = 13983816