recursive factorial function
74,291
Solution 1
We can combine the two functions to this single recursive function:
def factorial(n):
if n < 1: # base case
return 1
else:
returnNumber = n * factorial(n - 1) # recursive call
print(str(n) + '! = ' + str(returnNumber))
return returnNumber
Solution 2
2 lines of code:
def fac(n):
return 1 if (n < 1) else n * fac(n-1)
Test it:
print fac(4)
Result:
24
Solution 3
def factorial(n):
result = 1 if n <= 1 else n * factorial(n - 1)
print '%d! = %d' % (n, result)
return result
Solution 4
a short one:
def fac(n):
if n == 0:
return 1
else:
return n * fac(n-1)
print fac(0)
Solution 5
try this:
def factorial( n ):
if n <1: # base case
print "%2d! = %d" % (n, n)
return 1
else:
temp = factorial( n - 1 )
print "%2d! = %d" % (n, n*temp)
return n * temp # recursive call
One thing I noticed is that you are returning '1' for n<1, that means your function will return 1 even for negative numbers. You may want to fix that.
Author by
user531225
Updated on July 01, 2021Comments
-
user531225 almost 3 years
How can I combine these two functions into one recursive function to have this result:
factorial(6) 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720
This is the current code for my factorial function:
def factorial(n): if n < 1: # base case return 1 else: return n * factorial(n - 1) # recursive call def fact(n): for i in range(1, n+1 ): print "%2d! = %d" % (i, factorial(i))
and the output that this code produces is the following:
fact(6) 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720
As you see, the execution of these two functions gives me correct answers, but I just wanted to simplify the two functions to a single recursive function.
-
FrustratedWithFormsDesigner over 13 yearsI'm not 100% sure that this is correct, but since OP said it's for an exam, I won't go into any further details...
-
Tadeck over 12 years@D.Shawley: This is quite inefficient solution, as you calculate factorial(1)
n
times, factorial(2)n-1
times, factorial(3)n-2
times and so on... -
mcocdawc about 8 yearsMathematically 0! evaluates to 1. So the first part of your conditional should be changed.
-
imbatman over 5 yearsyou will have a recursion error as you don't handle 0 and below
-
TrebledJ over 5 yearsAlthough correct, the
while
is redundant asreturn
will kick in on the first iteration (and no other iterations will be performed). Changingwhile
toif
is much better. -
TrebledJ over 5 yearsWhat I meant by redundant was the communicative aspect... other coders seeing the function will see
while
and think: "Okay, it's factorial by looping"; then one line later they seereturn
and realise it's actually factorial by recursion. (Usually, recursion is a substitute for loops.) And... ah, I see a benchmark. A small difference in performance between while and if, but your new content seems well researched. :-) -
cdlane about 3 yearsThis doesn't work. The second reference to
factorial()
should instead bef()