pythonpython-3.xpython-2.7recursionspyder

How to fully understand and implement a recursive factorial function?


Lately I found out that I can't get what I want to have, like getting the Negative Integers of the factorial of this:

def rec_fac(n):
   if n == 1:
       return n
   else:
       return n*rec_fac(n-1)

if you have something to add with this code.. Leave a comment =)

thanks in advance!


Solution

  • Not sure what the question is, but factorial is defined for natural numbers.

    So to handle negative numbers, do this:

    def rec_fac(n):
       if n < 1:
           raise NotImplementedError('no definition for rec_fact(x) for x < 1')
       if n == 1:
           return n
       else:
           return n*rec_fac(n-1)