SHARE
TWEET

Python - factorial with cache

furas Jun 4th, 2018 (edited) 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top