Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. ### current bpython session - make changes and save to reevaluate session.
  2. ### lines beginning with ### will be ignored.
  3. ### To return to bpython without reevaluating make no changes to this file
  4. ### or save an empty file.
  5. class Int(int):
  6. def __call__(self, val):
  7. return Int(self + val)
  8.  
  9.  
  10. num = Int(1)
  11. num(2)
  12. ### 3
  13. num(3)(4)(5)(6), 1 + 3 + 4 + 5 + 6
  14. ### (19, 19)
  15.  
  16.  
  17. class CachedFibonacci:
  18. def __init__(self):
  19. self._cache = {}
  20.  
  21. def __call__(self, n):
  22. nth = None
  23. if n in self._cache:
  24. return self._cache[n]
  25. elif n in [1, 0]:
  26. nth = 1
  27. else:
  28. nth = self(n-1) + self(n-2)
  29. self._cache[n] = nth
  30. return nth
  31.  
  32. fib = CachedFibonacci()
  33. fib(3)
  34. ### 3
  35. fib._cache
  36. ### {0: 1, 1: 1, 2: 2, 3: 3}
  37. fib(6)
  38. ### 13
  39. fib._cache
  40. ### {0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8, 6: 13}
  41. ###
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement