|
| 1 | +# x is positional-only (default 0), e is positional-or-keyword (default 1) |
| 2 | +custom_power = lambda x=0, /, e=1: x**e |
| 3 | + |
| 4 | + |
| 5 | +def custom_equation( |
| 6 | + x: int = 0, y: int = 0, /, a: int = 1, b: int = 1, *, c: int = 1 |
| 7 | +) -> float: |
| 8 | + """ |
| 9 | + Calculate (x**a + y**b) / c. |
| 10 | +
|
| 11 | + :param x: Positional-only base of the first term. |
| 12 | + :type x: int |
| 13 | + :param y: Positional-only base of the second term. |
| 14 | + :type y: int |
| 15 | + :param a: Exponent applied to x. |
| 16 | + :type a: int |
| 17 | + :param b: Exponent applied to y. |
| 18 | + :type b: int |
| 19 | + :param c: Keyword-only divisor. |
| 20 | + :type c: int |
| 21 | + :return: The value of (x**a + y**b) / c. |
| 22 | + :rtype: float |
| 23 | + """ |
| 24 | + return (x**a + y**b) / c |
| 25 | + |
| 26 | + |
| 27 | +_total_calls: int = 0 |
| 28 | +_calls_by_caller: dict[str, int] = {} |
| 29 | + |
| 30 | + |
| 31 | +def fn_w_counter() -> (int, dict[str, int]): |
| 32 | + """ |
| 33 | + Count how many times this function has been called, and by whom. |
| 34 | +
|
| 35 | + :return: A tuple of the total number of calls and a dictionary mapping |
| 36 | + each caller's ``__name__`` to the number of calls it made. |
| 37 | + :rtype: tuple[int, dict[str, int]] |
| 38 | + """ |
| 39 | + global _total_calls |
| 40 | + _total_calls += 1 |
| 41 | + _calls_by_caller[__name__] = _calls_by_caller.get(__name__, 0) + 1 |
| 42 | + return _total_calls, dict(_calls_by_caller) |
| 43 | + |
| 44 | + |
| 45 | +if __name__ == "__main__": |
| 46 | + assert custom_power(2) == 2 |
| 47 | + assert custom_power(2, 3) == 8 |
| 48 | + assert custom_power(2, e=2) == 4 |
| 49 | + |
| 50 | + assert custom_equation(2, 3) == 5.0 |
| 51 | + assert custom_equation(2, 3, 2) == 7.0 |
| 52 | + assert custom_equation(2, 3, 2, 3) == 31.0 |
| 53 | + assert custom_equation(3, 5, a=2, b=3, c=4) == 33.5 |
| 54 | + assert custom_equation(3, 5, 2, b=3, c=4) == 33.5 |
| 55 | + assert custom_equation(3, 5, 2, 3, c=4) == 33.5 |
| 56 | + |
| 57 | + for i in range(10): |
| 58 | + fn_w_counter() |
| 59 | + assert fn_w_counter() == (11, {"__main__": 11}) |
| 60 | + print("All examples pass.") |
0 commit comments