11

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.

Alan Bagel
  • 818
  • 5
  • 24
user531225
  • 1,499
  • 4
  • 12
  • 15
  • 7
    I don't get any reason to combine both into one function. – mqpasta Dec 21 '10 at 18:08
  • 1
    Hmm. Is this homework? What have you tried so far? – Jason Orendorff Dec 21 '10 at 18:08
  • 1
    Don't. It looks fine the way it is. Combining them will just make things more difficult. – FrustratedWithFormsDesigner Dec 21 '10 at 18:08
  • @ FrustratedWithFormsDesigner: last year exam ... hahah .... I wish I could take you guys with me to write my exam for me but it's not possible :P – user531225 Dec 21 '10 at 18:14
  • The asker had possibly graduated since the question was set. Anyway, I hope the teacher who wanted them to implement the *factorial recursively* told them that the efficiency of the recursive solution is so terrible that it should never be allowed. :) – pepr Apr 25 '19 at 07:49

15 Answers15

31

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
Alan Bagel
  • 818
  • 5
  • 24
pythonFoo
  • 2,194
  • 3
  • 15
  • 17
26

2 lines of code:

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

Test it:

print fac(4)

Result:

24
martynas
  • 12,120
  • 3
  • 55
  • 60
7
def factorial(n):
    result = 1 if n <= 1 else n * factorial(n - 1)
    print '%d! = %d' % (n, result)
    return result
Will McCutchen
  • 13,047
  • 3
  • 44
  • 43
5

a short one:

def fac(n):
    if n == 0:
        return 1
    else:
        return n * fac(n-1)
print fac(0)
Ilyas
  • 59
  • 1
  • 1
4

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
Tadeck
  • 132,510
  • 28
  • 152
  • 198
Mchl
  • 61,444
  • 9
  • 118
  • 120
4

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.

Vinay Pandey
  • 1,129
  • 3
  • 16
  • 33
3

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.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113
  • @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... – Tadeck Jan 29 '12 at 00:20
2
fac = lambda x: 1 if x == 0 else x * fac(x - 1)
T-kin-ter
  • 99
  • 9
1

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))
zganger
  • 3,572
  • 1
  • 10
  • 13
MattyW
  • 1,519
  • 3
  • 16
  • 33
0

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'
Alan Bagel
  • 818
  • 5
  • 24
Salah Hamza
  • 89
  • 2
  • 6
0

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)))
0 _
  • 10,524
  • 11
  • 77
  • 109
Meir Keller
  • 511
  • 1
  • 7
  • 21
0

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
Szczerski
  • 839
  • 11
  • 11
  • Although correct, the `while` is redundant as `return` will kick in on the first iteration (and no other iterations will be performed). Changing `while` to `if` is much better. – TrebledJ Mar 26 '19 at 10:00
  • What 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 see `return` 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. :-) – TrebledJ Mar 26 '19 at 11:35
0

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
-1

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.

Robson
  • 813
  • 5
  • 21
  • 40
Ali
  • 1
  • 1
-2

One more =)

#FAC calculation

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


print (fakulteta(12))
XraySensei
  • 167
  • 7