>>> def fact(x):
... if x == 0:
... return 1
... else:
... return x * fact(x-1)
...
>>>
>>> fact(4)
24
-----------------------
def a(n):
f = 1
for x in range(1, n+1):
f *= x
print "fact : ", f
a(4)
-----------------------
>>> n=4
>>> reduce(int.__mul__, range(1, n+1))
24
or
>>> fact = lambda n : reduce(int.__mul__, range(1, n+1))
>>> fact(4)
24
-----------------------
>>> n=4
>>> reduce(lambda x,y:x*y, range(1, n+1))
24
or
>>> fact = lambda n : reduce(lambda x,y:x*y, range(1, n+1))
>>> fact(4)
24
-----------------------
>>> int.__mul__(3,4)
12
>>> import operator
>>> n=4
>>> reduce(operator.mul, range(1, n+1))
24
or
>>> import operator
>>> fact = lambda n : reduce(operator.mul, range(1, n+1))
>>> fact(4)
24
-----------------------
>>> def factorial(n):
... x = n
... for j in range(1, n):
... x = j*x
... return x
...
>>>
>>> factorial(4)
24
No comments:
Post a Comment