Advertisement
NLinker

10 ways to write a factorial function in Python

Feb 27th, 2017
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. # from http://www.senktec.com/2013/09/one-way-to-do-it/
  2.  
  3. def f1(n):
  4.   if n > 1:
  5.     return n * f1(n - 1)
  6.   else:
  7.     return 1
  8.  
  9. def f2(n):
  10.   return n * f2(n - 1) if n > 1 else 1
  11.  
  12. def f3(n):
  13.   if n <= 1: return 1
  14.   else: return f3(n - 1) * n
  15.  
  16. def f4(n, accumulator=1):
  17.   if n == 0:
  18.     return accumulator
  19.   else:
  20.     return f4(n - 1, accumulator * n)
  21.  
  22. f5 = lambda n: n and n * f5(n - 1) or 1
  23.  
  24. def f6(n):
  25.   result = 1
  26.   for i in range(1, n + 1):
  27.     result *= i
  28.   return result
  29.  
  30. def f7(n):
  31.   result = 1
  32.   while n > 0:
  33.     result *= n
  34.     n -= 1
  35.   return result
  36.  
  37. def f8(n):
  38.   if n == 0:
  39.     return 1
  40.   else:
  41.     return reduce(lambda a,b: a * b, range(1, n + 1))
  42.  
  43. def f9(n):
  44.   numbers = xrange(1, n + 1)
  45.   if len(numbers) == 0:
  46.     return 1
  47.   return reduce(int.__mul__, numbers)
  48.  
  49. def f10(n):
  50.   if n == 0: return 1
  51.   return eval('*'.join([str(i) for i in range(1, n + 1)]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement