1
0

73_functools.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # test reduce
  2. from functools import reduce, partial
  3. # test reduce
  4. assert reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) == 15
  5. assert reduce(lambda x, y: x * y, [1, 2, 3, 4, 5]) == 120
  6. assert reduce(lambda x, y: x * y, [1, 2, 3, 4, 5], 10) == 1200
  7. # test partial
  8. def add(a, b):
  9. return a + b
  10. add_1 = partial(add, 1)
  11. assert add_1(2) == 3
  12. assert add_1(3) == 4
  13. def sub(a, b=1):
  14. return a - b
  15. sub_10 = partial(sub, b=10)
  16. assert sub_10(20) == 10
  17. assert sub_10(30) == 20
  18. # test lru_cache
  19. from functools import lru_cache
  20. miss_keys = []
  21. @lru_cache(maxsize=3)
  22. def test_f(x: int):
  23. miss_keys.append(x)
  24. return x
  25. assert test_f(1) == 1 and miss_keys == [1]
  26. # [1]
  27. assert test_f(2) == 2 and miss_keys == [1, 2]
  28. # [1, 2]
  29. assert test_f(3) == 3 and miss_keys == [1, 2, 3]
  30. # [1, 2, 3]
  31. assert test_f(1) == 1 and miss_keys == [1, 2, 3]
  32. # [2, 3, 1]
  33. assert test_f(2) == 2 and miss_keys == [1, 2, 3]
  34. # [3, 1, 2]
  35. assert test_f(4) == 4 and miss_keys == [1, 2, 3, 4]
  36. # [1, 2, 4]
  37. assert test_f(3) == 3 and miss_keys == [1, 2, 3, 4, 3]
  38. # [2, 4, 3]
  39. assert test_f(2) == 2 and miss_keys == [1, 2, 3, 4, 3]
  40. # [4, 3, 2]
  41. assert test_f(5) == 5 and miss_keys == [1, 2, 3, 4, 3, 5]
  42. # [3, 2, 5]
  43. assert test_f(3) == 3 and miss_keys == [1, 2, 3, 4, 3, 5]
  44. # [2, 5, 3]
  45. assert test_f(1) == 1 and miss_keys == [1, 2, 3, 4, 3, 5, 1]
  46. # [5, 3, 1]