Skip to content

Commit d204137

Browse files
authored
Merge pull request #720 from EsraSepik/patch-4
Fix return statement formatting in functions_esra_sepik.py
2 parents 30aa1bb + 899090b commit d204137

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎Week04/decorators_esra_sepik.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import time
2+
import tracemalloc
3+
4+
5+
def performance(fn):
6+
"""
7+
Decorator that measures the execution time and memory usage of a function.
8+
Statistics are kept in performance.counter, performance.total_time
9+
and performance.total_mem.
10+
"""
11+
def _inner(*args, **kwargs):
12+
tracemalloc.start()
13+
begin = time.time()
14+
output = fn(*args, **kwargs)
15+
end = time.time()
16+
used = tracemalloc.get_traced_memory()[1]
17+
tracemalloc.stop()
18+
19+
setattr(performance, "counter", getattr(performance, "counter", 0) + 1)
20+
setattr(performance, "total_time", getattr(performance, "total_time", 0) + (end - begin))
21+
setattr(performance, "total_mem", getattr(performance, "total_mem", 0) + used)
22+
return output
23+
24+
_inner.__name__ = fn.__name__
25+
_inner.__doc__ = fn.__doc__
26+
return _inner
27+
28+
29+
performance.counter = 0
30+
performance.total_time = 0
31+
performance.total_mem = 0

‎Week04/functions_esra_sepik.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
custom_power = lambda x=0, /, e=1: x ** e
2+
3+
4+
def custom_equation(x: int = 0, y: int = 0, /, a: int = 1, b: int = 1, *, c: int = 1) -> float:
5+
"""
6+
Calculates an equation using the given integers.
7+
8+
The formula is ``(x ** a + y ** b) / c``.
9+
10+
:param x: positional-only value, defaults to 0
11+
:type x: int
12+
:param y: positional-only value, defaults to 0
13+
:type y: int
14+
:param a: exponent for x, defaults to 1
15+
:type a: int
16+
:param b: exponent for y, defaults to 1
17+
:type b: int
18+
:param c: keyword-only divisor, defaults to 1
19+
:type c: int
20+
:returns: the result of the equation
21+
:rtype: float
22+
"""
23+
numerator = pow(x, a) + pow(y, b)
24+
return numerator / c
25+
26+
27+
_call_count = 0
28+
_caller_counts: dict[str, int] = {}
29+
30+
31+
def fn_w_counter() -> (int, dict[str, int]):
32+
global _call_count
33+
caller_name = globals()["__name__"]
34+
_call_count += 1
35+
_caller_counts[caller_name] = _caller_counts.setdefault(caller_name, 0) + 1
36+
return (_call_count, dict(_caller_counts))

0 commit comments

Comments
 (0)