Skip to content

Commit 9a399e7

Browse files
authored
Merge pull request #761 from batyou0ne/patch-5
Implement custom power and equation functions
2 parents f103f58 + 93776ca commit 9a399e7

1 file changed

Lines changed: 69 additions & 0 deletions

File tree

‎Week04/functions_batuhan_keskin.py‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""Week04 - Introduction to Python: functions."""
2+
3+
# x positional-only (default 0), e positional-or-keyword (default 1)
4+
custom_power = lambda x=0, /, e=1: x ** e
5+
6+
7+
def custom_equation(
8+
x: int = 0,
9+
y: int = 0,
10+
/,
11+
a: int = 1,
12+
b: int = 1,
13+
*,
14+
c: int = 1,
15+
) -> float:
16+
"""
17+
Calculate (x**a + y**b) / c.
18+
19+
:param x: first base (positional-only)
20+
:type x: int
21+
:param y: second base (positional-only)
22+
:type y: int
23+
:param a: exponent of x (positional-or-keyword)
24+
:type a: int
25+
:param b: exponent of y (positional-or-keyword)
26+
:type b: int
27+
:param c: divisor (keyword-only)
28+
:type c: int
29+
:return: the value of (x**a + y**b) / c
30+
:rtype: float
31+
"""
32+
return (x ** a + y ** b) / c
33+
34+
35+
_call_counts: dict[str, int] = {}
36+
_total_calls: int = 0
37+
38+
39+
def fn_w_counter() -> (int, dict[str, int]):
40+
"""
41+
Count the calls made to this function together with caller information.
42+
43+
:return: total number of calls and a dictionary mapping each caller's
44+
``__name__`` to the number of calls made from that caller
45+
:rtype: tuple[int, dict[str, int]]
46+
"""
47+
global _total_calls
48+
caller = __name__
49+
_total_calls += 1
50+
_call_counts[caller] = _call_counts.get(caller, 0) + 1
51+
return _total_calls, dict(_call_counts)
52+
53+
54+
if __name__ == "__main__":
55+
assert custom_power(2) == 2
56+
assert custom_power(2, 3) == 8
57+
assert custom_power(2, e=2) == 4
58+
59+
assert custom_equation(2, 3) == 5.0
60+
assert custom_equation(2, 3, 2) == 7.0
61+
assert custom_equation(2, 3, 2, 3) == 31.0
62+
assert custom_equation(3, 5, a=2, b=3, c=4) == 33.5
63+
assert custom_equation(3, 5, 2, b=3, c=4) == 33.5
64+
assert custom_equation(3, 5, 2, 3, c=4) == 33.5
65+
66+
for i in range(10):
67+
fn_w_counter()
68+
assert fn_w_counter() == (11, {'__main__': 11})
69+
print("All examples passed.")

0 commit comments

Comments
 (0)