Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorial function in Python

Tags:

python

I am new to Python, and am just learning the syntax and various functions. I would like to know if

x=reduce((lambda x,y: x*y) , [x for x in range(5) if x > 0])

is a correct function for calculating the factorial of a number ?

Kind Regards

like image 539
AndroidDev Avatar asked Mar 08 '26 20:03

AndroidDev


1 Answers

Something along the lines of http://www.willamette.edu/~fruehr/haskell/evolution.html

# beginner

def fac(n):
    f = 1
    i = 1
    while i <= n:
        f *= i
        i += 1
    return f

# advanced beginner

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

# intermediate

def fac(n):
    return reduce(lambda x, y: x * y, range(1, n + 1))

# advanced intermediate

import operator
def fac(n):
    return reduce(operator.mul, xrange(1, n + 1))

# professional

import math
print math.factorial(5)

# guru

import scipy.misc as sc
print sc.factorial(5, exact=True)
like image 134
georg Avatar answered Mar 11 '26 10:03

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!