fork download
  1. import math
  2.  
  3. def caching(func):
  4. cache = {}
  5. def wrapped_func(*args):
  6. argstr = '({})'.format(', '.join(map(str, args)))
  7. if args not in cache:
  8. print(f'> calculating {func.__name__}{argstr}')
  9. cache[args] = func(*args)
  10. else:
  11. print(f'> reusing cached result for {func.__name__}{argstr}')
  12. return cache[args]
  13. return wrapped_func
  14.  
  15. @caching
  16. def my_multiply(x, y):
  17. return x * y
  18.  
  19. @caching
  20. def my_divide(x, y):
  21. return x / y
  22.  
  23. @caching
  24. def my_hypot(a, b):
  25. return math.sqrt(a * a + b * b)
  26.  
  27. print(my_multiply(2, 2))
  28. print(my_divide(2, 2))
  29. print(my_multiply(2, 2))
  30. print(my_divide(2, 2))
  31. print(my_hypot(2, 3))
  32. print(my_divide(2, 3))
  33. print(my_hypot(2, 3))
  34. print(my_hypot(3, 3))
Success #stdin #stdout 0.02s 9284KB
stdin
Standard input is empty
stdout
> calculating my_multiply(2, 2)
4
> calculating my_divide(2, 2)
1.0
> reusing cached result for my_multiply(2, 2)
4
> reusing cached result for my_divide(2, 2)
1.0
> calculating my_hypot(2, 3)
3.605551275463989
> calculating my_divide(2, 3)
0.6666666666666666
> reusing cached result for my_hypot(2, 3)
3.605551275463989
> calculating my_hypot(3, 3)
4.242640687119285