Python Efficient Factorial Calculation in Python: Recursive vs. Iterative Methods

  • Thread starter Thread starter Whovian
  • Start date Start date
  • Tags Tags
    Bit Python
AI Thread Summary
The discussion centers on a Python implementation of functions to calculate combinations using factorials. The initial code attempts to compute binomial coefficients but encounters a recursion error due to the factorial function not handling negative inputs, which can lead to infinite recursion. It is emphasized that factorials are undefined for negative numbers, suggesting the need for input validation and exception handling to enhance the robustness of the code. Additionally, the inefficiency of using a recursive approach for factorial calculations in Python is noted, with an alternative iterative method provided. Performance comparisons using the `timeit` module reveal that the iterative method is significantly faster than the recursive one. The conversation also touches on programming practices, debating the necessity of defensive programming versus practical application scenarios, such as web apps where precomputed values might be more efficient.
Whovian
Messages
651
Reaction score
3
I tried the following code:

Code:
def factorial(n):
    if (n == 0):
        return 1
    else:
        return n*factorial(n-1)

def ncr(n,r):
    return ((factorial(n))/(factorial(r)*factorial(n-r)))

number = 0

for n in range(100):
    for r in range(100):
        print ncr(n,r)

Basically, for all n and r from 1 to 100, it's supposed to print ##\binom{n}{r}##

Unfortunately, running from the command line, I get:

Code:
Traceback (most recent call last):
  File "Pythontest.py", line 14, in <module>
    print ncr(n,r)
  File "Pythontest.py", line 8, in ncr
    return ((factorial(n))/(factorial(r)*factorial(n-r)))
  File "Pythontest.py", line 5, in factorial
    return n*factorial(n-1)
  File "Pythontest.py", line 5, in factorial
    return n*factorial(n-1)
  File "Pythontest.py", line 5, in factorial
    return n*factorial(n-1)
 
Technology news on Phys.org
you have to have 0 \le r \le n. your definition of factorial goes into an infinite callback if n &lt; 0.
 
Also, for general purposes...factorial is not defined for negative numbers, so, you should enhance your 'def factorial' and guard (validate) against negative numbers and possibly raise an exception, etc...you know, for when you use this def in a more complex program.
 
Dickfore said:
you have to have 0 \le r \le n. your definition of factorial goes into an infinite callback if n &lt; 0.

Oh. Oops.

gsal said:
Also, for general purposes...factorial is not defined for negative numbers, so, you should enhance your 'def factorial' and guard (validate) against negative numbers and possibly raise an exception, etc...you know, for when you use this def in a more complex program.

Also sound advice.
 
May I ask why you are doing it recursively? It's not particularly efficient in Python when done that way.

Code:
def rfac (x):
    return x * rfac (x-1) if x > 0 else 1
    
def ifac (x):
    f = 1
    for i in range (1, x+1):
        f *= i
    return f

from timeit import Timer
print (Timer ("rfac(20)", "from __main__ import rfac")).timeit()
print (Timer ("ifac(20)", "from __main__ import ifac")).timeit()

$ python fac.py
10.4178638458
5.76771497726

There are much faster ways to compute it, if you search the web.

Edit: I am not sure I would check or throw for negative input. There's defensive programming, and there's paranoia. It should not happen in practice. I admit this is personal style. I understand there cases where it might (web app), but seriously ... use a precomputed lookup table of N! if it's a web app.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Replies
19
Views
2K
Replies
9
Views
3K
Replies
11
Views
1K
Replies
18
Views
1K
Replies
15
Views
2K
Replies
7
Views
5K
Replies
8
Views
1K
Back
Top