diff --git a/Week04/decorators_esra_sepik.py b/Week04/decorators_esra_sepik.py new file mode 100644 index 00000000..bc34edf3 --- /dev/null +++ b/Week04/decorators_esra_sepik.py @@ -0,0 +1,31 @@ +import time +import tracemalloc + + +def performance(fn): + """ + Decorator that measures the execution time and memory usage of a function. + Statistics are kept in performance.counter, performance.total_time + and performance.total_mem. + """ + def _inner(*args, **kwargs): + tracemalloc.start() + begin = time.time() + output = fn(*args, **kwargs) + end = time.time() + used = tracemalloc.get_traced_memory()[1] + tracemalloc.stop() + + setattr(performance, "counter", getattr(performance, "counter", 0) + 1) + setattr(performance, "total_time", getattr(performance, "total_time", 0) + (end - begin)) + setattr(performance, "total_mem", getattr(performance, "total_mem", 0) + used) + return output + + _inner.__name__ = fn.__name__ + _inner.__doc__ = fn.__doc__ + return _inner + + +performance.counter = 0 +performance.total_time = 0 +performance.total_mem = 0 diff --git a/Week04/functions_esra_sepik.py b/Week04/functions_esra_sepik.py new file mode 100644 index 00000000..18dc055b --- /dev/null +++ b/Week04/functions_esra_sepik.py @@ -0,0 +1,36 @@ +custom_power = lambda x=0, /, e=1: x ** e + + +def custom_equation(x: int = 0, y: int = 0, /, a: int = 1, b: int = 1, *, c: int = 1) -> float: + """ + Calculates an equation using the given integers. + + The formula is ``(x ** a + y ** b) / c``. + + :param x: positional-only value, defaults to 0 + :type x: int + :param y: positional-only value, defaults to 0 + :type y: int + :param a: exponent for x, defaults to 1 + :type a: int + :param b: exponent for y, defaults to 1 + :type b: int + :param c: keyword-only divisor, defaults to 1 + :type c: int + :returns: the result of the equation + :rtype: float + """ + numerator = pow(x, a) + pow(y, b) + return numerator / c + + +_call_count = 0 +_caller_counts: dict[str, int] = {} + + +def fn_w_counter() -> (int, dict[str, int]): + global _call_count + caller_name = globals()["__name__"] + _call_count += 1 + _caller_counts[caller_name] = _caller_counts.setdefault(caller_name, 0) + 1 + return (_call_count, dict(_caller_counts))