Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Week04/decorators_jalil_guliyev.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@

"""Week 04: Decorators homework."""

import functools
import time
import tracemalloc


def performance(func):
"""Track cumulative calls, elapsed time and peak memory allocation."""

@functools.wraps(func)
def wrapper(*args, **kwargs):
tracing_started_here = not tracemalloc.is_tracing()

if tracing_started_here:
tracemalloc.start()

before_current, before_peak = tracemalloc.get_traced_memory()
start = time.perf_counter()

try:
return func(*args, **kwargs)

finally:
elapsed = time.perf_counter() - start
current, peak = tracemalloc.get_traced_memory()

allocated = max(0, peak - before_current)

performance.counter += 1
performance.total_time += elapsed
performance.total_mem += allocated

if tracing_started_here:
tracemalloc.stop()

return wrapper


performance.counter = 0
performance.total_time = 0.0
performance.total_mem = 0
36 changes: 36 additions & 0 deletions Week04/functions_jalil_guliyev.py
Original file line number Diff line number Diff line change
@@ -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:
"""Calculate the result of an equation.

:param x: First base.
:param y: Second base.
:param a: Exponent of x.
:param b: Exponent of y.
:param c: Divisor.
:return: The result of (x**a + y**b) / c.
"""
if any(type(value) is not int for value in (x, y, a, b, c)):
raise TypeError("All parameters must be integers")

return (x ** a + y ** b) / c


def fn_w_counter() -> (int, dict[str, int]):
if not hasattr(fn_w_counter, "counter"):
fn_w_counter.counter = 0
fn_w_counter.callers = {}

fn_w_counter.counter += 1
caller = __name__
fn_w_counter.callers[caller] = (
fn_w_counter.callers.get(caller, 0) + 1
)

return fn_w_counter.counter, fn_w_counter.callers.copy()