Skip to content

Commit 920ad49

Browse files
authored
Add custom power and equation functions with counter
This file includes custom functions for power calculation, equation evaluation, and counting function calls.
1 parent 5ae1705 commit 920ad49

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Week04/functions_heval_sogut.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# custom_power
2+
custom_power = lambda x=0, /, e=1: x**e
3+
4+
# custom_equation
5+
def custom_equation(x: int = 0, y: int = 0, /, a: int = 1, b: int = 1, *, c: int = 1) -> float:
6+
"""
7+
Calculates the result of the equation (x**a + y**b) / c.
8+
9+
:param x: The first base number (positional-only).
10+
:param y: The second base number (positional-only).
11+
:param a: The exponent for x (positional-or-keyword).
12+
:param b: The exponent for y (positional-or-keyword).
13+
:param c: The divisor (keyword-only).
14+
:return: The float result of the equation.
15+
"""
16+
# Manual type checking to raise TypeError
17+
if not isinstance(x, int):
18+
raise TypeError("x must be an integer")
19+
if not isinstance(y, int):
20+
raise TypeError("y must be an integer")
21+
if not isinstance(a, int):
22+
raise TypeError("a must be an integer")
23+
if not isinstance(b, int):
24+
raise TypeError("b must be an integer")
25+
if not isinstance(c, int):
26+
raise TypeError("c must be an integer")
27+
28+
# The calculation, which will return a float
29+
return (x**a + y**b) / c
30+
31+
# fn_w_counter
32+
def fn_w_counter() -> (int, dict[str, int]):
33+
"""
34+
Counts the total number of times this function has been called.
35+
36+
This function uses an attribute 'count' on itself to store the call count,
37+
avoiding the use of a global variable.
38+
39+
Returns the total count and a dictionary where the key is this
40+
module's __name__ and the value is the total count.
41+
42+
:return: A tuple of (total_calls, {__name__: total_calls})
43+
:rtype: (int, dict[str, int])
44+
"""
45+
# Initialize the counter on the function object if it doesn't exist
46+
if not hasattr(fn_w_counter, "count"):
47+
fn_w_counter.count = 0
48+
49+
# Increment the counter
50+
fn_w_counter.count += 1
51+
52+
# Return the total count and the dictionary as specified
53+
return (fn_w_counter.count, {__name__: fn_w_counter.count})

0 commit comments

Comments
 (0)