Factorial


#1

my version:

def factorial(x):
    x = abs(x)
    
    if x == 0 or x == 1:
        x = 1
    else:
        for i in range(1, x + 1):
            x = i * factorial(i - 1)
    return x
    
print factorial(-4)

anybody could explain why version without 'for' loop also works? :slight_smile: and how?


Factorial query
#3

Its a recursive solution, its explained nicely here:

the function just calls itself for all possible numbers until base case is reached, then it reverses back through the function calls


#4

When using a loop construct, there would be no need for recursion.


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

When using recursion, the looping is part of the process of building the call stack, then winding it down at the end.


def factorial(n):
    return 1 if n < 1 else n * factorial(n - 1)

As to our function converting inputs, that is not the its job. If the program is being given invalid inputs it should raise an exception so the bug that causes the invalid value is revealed and can be located and fixed.

if x < 0:
    raise ValueError

#5

#6

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