Recursive factor function

how can I combine these two functions into one recursive function to get this result:

factorial(6) 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 

these are codes

 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 ) ) fact(6) 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 

as you see, the execution of these two gives the correct answer, I just want to do it with one recursive function.

+8
python recursion factorial
source share
11 answers
 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 
+19
source share

2 lines of code:

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

Check this:

 print fac(4) 

Result:

 24 
+18
source share

short:

 def fac(n): if n == 0: return 1 else: return n * fac(n-1) print fac(0) 
+5
source share
 def factorial(n): result = 1 if n <= 1 else n * factorial(n - 1) print '%d! = %d' % (n, result) return result 
+4
source share

I have no experience with Python, but something like this?

 def factorial( n ): if n <1: # base case return 1 else: f = n * factorial( n - 1 ) # recursive call print "%2d! = %d" % ( n, f ) return f 
+2
source share

try the following:

 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, which means your function will return 1 even for negative numbers. You can fix it.

+2
source share

Is this homework possible?

 def traced_factorial(n): def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) for i in range(1, n + 1): print '%2d! = %d' %(i, factorial(i)) 

Give PEP227 for more details. In short, Python allows you to define functions inside functions.

+1
source share

One more

 def fact(x): if x == 0: return 0 elif x == 1: return 1 else: return x * fact(x-1) for x in range(0,10): print '%d! = %d' %(x, fact(x)) 
+1
source share
 fac = lambda x: 1 if x == 0 else x * fac(x - 1) 
+1
source share

If you want to receive information from the user!

 def factorial(number): return 1 if (number<1) else number * factorial(number-1) n = int(input().strip()) print("n! = 1", end="") for num in range(2, n+1): print(" x {}". format(num), end="") print(" = {}".format(factorial(n))) 
0
source share

I really don't know the factorial of negative numbers, but this will work with all n> = 0:

 def factorial(n): if n >= 0: if n == 1 or n==0: return 1 else: n = n * factorial(n-1) return n else: return 'error' 
0
source share

Source: https://habr.com/ru/post/650354/


All Articles