Skip to content

Commit cd87200

Browse files
committed
Add Week04 functions and decorators
1 parent 9a399e7 commit cd87200

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

‎Week04/decorators_beyza_arman.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from functools import wraps
2+
from time import perf_counter
3+
import tracemalloc
4+
5+
6+
def performance(function):
7+
"""Measure calls, elapsed time and peak traced memory."""
8+
@wraps(function)
9+
def wrapper(*args, **kwargs):
10+
owns_tracing = not tracemalloc.is_tracing()
11+
if owns_tracing:
12+
tracemalloc.start()
13+
before, _ = tracemalloc.get_traced_memory()
14+
start = perf_counter()
15+
try:
16+
return function(*args, **kwargs)
17+
finally:
18+
performance.counter += 1
19+
performance.total_time += perf_counter() - start
20+
_, peak = tracemalloc.get_traced_memory()
21+
performance.total_mem += max(0, peak - before)
22+
if owns_tracing:
23+
tracemalloc.stop()
24+
return wrapper
25+
26+
27+
performance.counter = 0
28+
performance.total_time = 0.0
29+
performance.total_mem = 0

‎Week04/functions_beyza_arman.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
custom_power = lambda x=0, /, e=1: x ** e
2+
3+
4+
def custom_equation(x: int = 0, y: int = 0, /,
5+
a: int = 1, b: int = 1, *, c: int = 1) -> float:
6+
"""Calculate a sum of powers divided by c.
7+
8+
:param x: First base.
9+
:param y: Second base.
10+
:param a: Exponent of x.
11+
:param b: Exponent of y.
12+
:param c: Divisor.
13+
:return: The value of (x**a + y**b) / c.
14+
:raises TypeError: If an argument is not an integer.
15+
"""
16+
if not all(isinstance(value, int) for value in (x, y, a, b, c)):
17+
raise TypeError("All arguments must be integers")
18+
return (x ** a + y ** b) / c
19+
20+
21+
def fn_w_counter() -> (int, dict[str, int]):
22+
"""Count calls and keep a per-module record."""
23+
fn_w_counter.counter += 1
24+
calls = fn_w_counter.calls
25+
calls[__name__] = calls.get(__name__, 0) + 1
26+
return fn_w_counter.counter, dict(calls)
27+
28+
29+
fn_w_counter.counter = 0
30+
fn_w_counter.calls = {}

0 commit comments

Comments
 (0)