Efficient Factorial Calculation in Python: Recursive vs. Iterative Methods

In summary, the conversation discusses a code for calculating combinations using the factorial function and a loop. However, the code produces an error due to negative numbers not being accounted for in the factorial function. The conversation also suggests using more efficient methods for computing factorials and discusses the use of defensive programming.
  • #1
Whovian
652
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
  • #2
you have to have [itex]0 \le r \le n[/itex]. your definition of factorial goes into an infinite callback if [itex]n < 0[/itex].
 
  • #3
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.
 
  • #4
Dickfore said:
you have to have [itex]0 \le r \le n[/itex]. your definition of factorial goes into an infinite callback if [itex]n < 0[/itex].

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.
 
  • #5
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.
 

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

1. What is Python and why is it used in science?

Python is a high-level, interpreted programming language that is commonly used in scientific fields. It is popular due to its simple syntax, versatility, and ability to handle large amounts of data. It is also open-source, making it easily accessible for researchers and scientists to use.

2. Can you explain what "a bit of trouble with Python" means?

"A bit of trouble with Python" is a phrase used to describe any difficulties or challenges that one may encounter while using the Python programming language. It could refer to a specific issue with code, understanding a concept, or troubleshooting a problem.

3. Is Python difficult to learn for scientists with no programming background?

Python is generally considered to be one of the easier programming languages to learn, even for those without a programming background. Its simple syntax and extensive documentation make it relatively accessible for beginners. However, like any new skill, it does require time and effort to become proficient.

4. What are some common applications of Python in scientific research?

Python has a wide range of applications in scientific research, including data analysis, machine learning, and statistical modeling. It is also commonly used for automating tasks and creating visualizations. Additionally, many scientific libraries and frameworks are built using Python, making it a popular choice for researchers.

5. Where can I find resources to learn more about Python for scientific use?

There are many online resources available for learning Python for scientific purposes. Some popular options include online courses, tutorials, and documentation from reputable sources such as Python.org and DataCamp. Additionally, many universities and research institutions offer workshops and classes on Python for scientists.

Similar threads

  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
19
Views
2K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
11
Views
834
  • Programming and Computer Science
Replies
15
Views
1K
  • Programming and Computer Science
Replies
34
Views
3K
  • Programming and Computer Science
Replies
18
Views
1K
Replies
9
Views
1K
  • Programming and Computer Science
Replies
7
Views
3K
  • Programming and Computer Science
2
Replies
55
Views
4K
Back
Top