Advertisement
furas

Python - factorial with cache

Jun 4th, 2018
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.49 KB | None | 0 0
  1. import time
  2.  
  3. cache = {}
  4.  
  5. def factorial(x):
  6.     if x in cache:
  7.         return cache[x]
  8.  
  9.     if x > 1:
  10.         value = x * factorial(x-1)
  11.     elif x > -1:
  12.         value = 1
  13.     else:
  14.         print('Wrong number')
  15.         exit(1)
  16.  
  17.     cache[x] = value
  18.     return value
  19.  
  20. start = time.time()
  21. result = factorial(980)
  22. end = time.time()
  23. print(end - start) # 0.002 second
  24.  
  25. start = time.time()
  26. result = factorial(980)
  27. end = time.time()
  28. print(end - start) # 0.000002 second (2.0e-06)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement