recursive factorial function

Question:

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.

Asked By: user531225

||

Answers:

I’ve 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
Answered By: Mchl

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.

Answered By: Vinay Pandey
def factorial(n):
    result = 1 if n <= 1 else n * factorial(n - 1)
    print '%d! = %d' % (n, result)
    return result
Answered By: Will McCutchen

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
Answered By: pythonFoo

Is this homework by any chance?

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 a read for more details. The short of it is that Python lets you define functions within functions.

Answered By: D.Shawley

One more

def fact(x):
    if x in {0, 1}:
        return 1
    else:
        return x * fact(x-1)

for x in range(0,10):
    print '%d! = %d' %(x, fact(x))
Answered By: MattyW

a short one:

def fac(n):
    if n == 0:
        return 1
    else:
        return n * fac(n-1)
print fac(0)
Answered By: Ilyas

2 lines of code:

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

Test it:

print fac(4)

Result:

24
Answered By: martynas
fac = lambda x: 1 if x == 0 else x * fac(x - 1)
Answered By: T-kin-ter

I don’t really 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

    return 'error'
Answered By: Salah Hamza

One more =)

#FAC calculation

def fakulteta(x):
    if x!=1:
         return x*fakulteta(x-1)
    return 1


print (fakulteta(12))
Answered By: XraySensei

Can use these 4 lines of code…

   def factorial(n):
        f = lambda n: n * f(n - 1) if n > 1 else 1

        for x in range(n):
            print('{}! = {}'.format(x + 1, factorial(x + 1)))
Answered By: Meir Keller

And for the first time calculate the factorial using recursive and the while loop.

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

Although the option that TrebledJ wrote in the comments about using if is better. Because while loop performs more operations (SETUP_LOOP, POP_BLOCK) than if. The function is slower.

def factorial(n):
    if  n >= 1:
        return n * factorial(n - 1)
    return 1

timeit -n 10000 -r 10

  • while 836 µs ± 11.8 µs per loop
  • if 787 µs ± 7.22 µs per loop
Answered By: Szczerski

There is always some kind of a loop in recursive functions and some stoping codes which stop the loop:

public int recursivefactorial(int number)
{
    if(number==1)
        return 1;
    else
        return recursivefactorial(number-1)*number;
}

As you can see the fulfilling the if condition leads to the code that actually ends the “loop” and this is the most important part of a recursive function. In contrast, the else part of the condition leads to calling recursivefactorial function once again which is effectively a kind of loop.

Answered By: Ali

In Python 3.8 you can try factorial function itself.

import math
n=int(input())
print(math.factorial(n))

For example:

Input: 5

Output:120
Answered By: İlaha Algayeva
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.