Factorial, I don't know whether I'm doing it right


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096#


The code works correctly but I think there should have been a shorter way. Help will be appreciated!


def factorial(x):
    total=[x]
    while x > 1:
        x=x-1
        total.append(x)
    multiply=1
    for each in total:
        multiply=multiply*each
    return multiply
print factorial(4)#This is just to test


#2

The way I did it was to assume that all numbers passed were positive.

def factorial(x):
    answer = 1
    for i in range(1, x + 1):
        answer *= i
    return answer

Set answer as 1 first because factorial(0) and factorial(1) are 1.
The range is set to x+1 because the range does not include the end, which means simply putting the stop at x would not include x itself. So with x+1, the function will allow answer to multiply by the original number.
Then let answer multiply by the numbers in the loop, 1, 2, 3... all the way up to the original number. answer *= i means the same as answer = answer * i.
Finally, return the final answer.


#3

There is a shorter way.
You can use the input as a counter(you need to start from the the number you got as input and count down... ) and delete one loop.(you will most likely to encounter methods like this in recursion)
this is my code :slight_smile:

def factorial(x):
result = 1
while x > 1:
result *= x
x -= 1
return result

any way our complicity is kind of the same...I hope this help :relaxed:


#4

Thanks!
I had tried something like this earlier on but hadn't worked.
I must have made a syntax error.
Thanks again.


#5

# Using for loop
def factorial(x):
    if x < 0:
        return "Factorial does not exist for negative integers."
    else:
        result = 1
        for i in range(1, x + 1):
            result *= i
        return result

# Using while loop
def factorial(x):
    if x < 0:
        return "Factorial does not exist for negative integers."
    else:
        result = 1
        while x >= 1:
            result *= x
            x -= 1
        return result

# If recursion is allowed
def factorial(x):
    if x < 0:
        return "Factorial does not exist for negative integers."
    if x == 0:
        return 1
    return x * factorial(x - 1)

FYI, there is also built-in factorial() in math module.

from math import factorial
print(factorial(x))     # Replace x with an integer >= 0

Hope that helps.


#6

Here's what I did. A slight variation on red-blacktree's response, but it worked well with the way I think of factorials.

def factorial(x):
output = x
while x > 1:
x = x - 1
output *= x
return output


#7

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