Advertisement
Korotkodul

B. Ложь, Наглая ложь и Статистика

Sep 21st, 2024 (edited)
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. import time
  2.  
  3. from typing import Callable, TypeVar
  4. from functools import wraps
  5.  
  6. T = TypeVar("T")
  7.  
  8. def is_floats_eq(lhs: float, rhs: float, eps: float = 1e-6) -> bool:
  9.     return abs(lhs - rhs) < eps
  10.  
  11. def collect_statistic(
  12.     statistics: dict[str, list[float, int]]
  13. ) -> Callable[[T], T]:
  14.     def recycle(func):
  15.         nonlocal statistics
  16.         @wraps(func)
  17.         def wrapper(*args, **kwargs):
  18.             start = time.time()
  19.             res = func()
  20.             end = time.time()
  21.             #print("check")
  22.             #print("func", func.__name__)
  23.             if func.__name__ not in statistics.keys():
  24.                 #print("zero")
  25.                 statistics[func.__name__] = [0.0, 0]
  26.             #print("check done")
  27.             n = statistics[func.__name__][1]
  28.             statistics[func.__name__][1] += 1
  29.             statistics[func.__name__][0] = (statistics[func.__name__][0] * n  +  end - start) / (n + 1)
  30.             #print("statistics", statistics)
  31.             #print()
  32.             return res
  33.         return wrapper
  34.     return recycle
  35.  
  36. statistics: list[str, list[float, int]] = {}
  37. #сверху или снизу?
  38.  
  39. @collect_statistic(statistics)
  40. def func1() -> None:
  41.     time.sleep(2)
  42.     #print(statistics)
  43.  
  44.  
  45. @collect_statistic(statistics)
  46. def func2() -> None:
  47.     time.sleep(1)
  48.     #print(statistics)
  49.  
  50. #print("func1")
  51. for i in range(3):
  52.     func1()
  53.  
  54. #print()
  55. #print("func2")
  56. for i in range(6):
  57.     func2()
  58.  
  59. eps = 1e-2
  60.  
  61. assert statistics[func1.__name__][1] == 3
  62. assert statistics[func2.__name__][1] == 6
  63. assert is_floats_eq(statistics[func1.__name__][0], 2, eps)
  64. assert is_floats_eq(statistics[func2.__name__][0], 1, eps)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement