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.

5
  • 7
    I don't get any reason to combine both into one function. Commented Dec 21, 2010 at 18:08
  • 1
    Hmm. Is this homework? What have you tried so far? Commented Dec 21, 2010 at 18:08
  • 1
    Don't. It looks fine the way it is. Combining them will just make things more difficult. Commented Dec 21, 2010 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 Commented Dec 21, 2010 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. :) Commented Apr 25, 2019 at 7:49

15 Answers 15

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 
Sign up to request clarification or add additional context in comments.

Comments

28

2 lines of code:

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

Test it:

print fac(4) 

Result:

24 

Comments

7
def factorial(n): result = 1 if n <= 1 else n * factorial(n - 1) print '%d! = %d' % (n, result) return result 

Comments

5

a short one:

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

Comments

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.

Comments

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 

1 Comment

I'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...
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.

1 Comment

@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...
2
fac = lambda x: 1 if x == 0 else x * fac(x - 1) 

Comments

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

1 Comment

Mathematically 0! evaluates to 1. So the first part of your conditional should be changed.
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

2 Comments

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.
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. :-)
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))) 

1 Comment

This doesn't work. The second reference to factorial() should instead be f()
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' 

Comments

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 

Comments

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

Comments

-2

One more =)

#FAC calculation def fakulteta(x): if x!=1: return x*fakulteta(x-1) return 1 print (fakulteta(12)) 

1 Comment

you will have a recursion error as you don't handle 0 and below

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.