Thursday, August 27, 2009

Writing factorial function in Python - newbie


The recursive version:

import sys

Usage = """
Usage:
$ python factorial.py
"""

def fact(x):
if x == 0:
return 1
else:
return x * fact(x-1)

if (len(sys.argv)>1) :
print fact(int(sys.argv[1]))
else:
print Usage

Executing:

$ python factorial.py 6
720

A shorter version of the above:

import sys

Usage = """
Usage:
$ python factorial.py
"""

def fact(x):
return (1 if x==0 else x * fact(x-1))

if (len(sys.argv)>1) :
print fact(int(sys.argv[1]))
else:
print Usage

Or a non-recursive version

def fact(x):
f = 1
while (x > 0):
f = f * x
x = x - 1
return f

And in python 2.6, Math module (Mathematical functions) provides factorial function (math.factorial(x))

$ /jks/bin/python2.6
Python 2.6.2 (r262:71600, Jun 17 2009, 22:31:41)
[GCC 3.3.3 (Debian 20040306)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.factorial(6)
720
>>>


Related concepts:
- Python math module

0 Comments: