845c3d0module-10: add ex3
1 file changed, +92, -0
@@ -0,0 +1,92 @@
1+from functools import reduce, partial, lru_cache, singledispatch
2+from operator import add, mul
3+from collections.abc import Callable
4+
5+
6+def spell_reducer(spells: list[int], operation: str) -> int:
7+ if not spells:
8+ return 0
9+ ops = {
10+ "add": add,
11+ "multiply": mul,
12+ "max": max,
13+ "min": min,
14+ }
15+ if operation not in ops:
16+ raise ValueError(f"Unknown operation: {operation}")
17+ if operation in ("max", "min"):
18+ return reduce(ops[operation], spells)
19+ return reduce(ops[operation], spells)
20+
21+
22+def partial_enchanter(base_enchantment: Callable) -> dict[str, Callable]:
23+ return {
24+ "fire": partial(base_enchantment, power=50, element="fire"),
25+ "ice": partial(base_enchantment, power=50, element="ice"),
26+ }
27+
28+
29+@lru_cache(maxsize=None)
30+def memoized_fibonacci(n: int) -> int:
31+ if n <= 1:
32+ return n
33+ return memoized_fibonacci(n - 1) + memoized_fibonacci(n - 2)
34+
35+
36+def spell_dispatcher() -> Callable:
37+ @singledispatch
38+ def dispatch(_) -> str:
39+ return "Unknown spell type"
40+
41+ @dispatch.register(int)
42+ def _(spell: int) -> str:
43+ return f"Damage spell: {spell} damage"
44+
45+ @dispatch.register(str)
46+ def _(spell: str) -> str:
47+ return f"Enchantment: {spell}"
48+
49+ @dispatch.register(list)
50+ def _(spell: list) -> str:
51+ return f"Multi-cast: {len(spell)} spells"
52+
53+ return dispatch
54+
55+
56+def base_enchant(target: str, power: int, element: str) -> str:
57+ return (
58+ f"{element.capitalize()} enchantment on {target} (power {power})"
59+ )
60+
61+
62+if __name__ == "__main__":
63+ print("Testing spell reducer...")
64+ spells = [10, 20, 30, 40]
65+ print(f"Add: {spell_reducer(spells, 'add')}")
66+ print(f"Multiply: {spell_reducer(spells, 'multiply')}")
67+ print(f"Max: {spell_reducer(spells, 'max')}")
68+ print(f"Min: {spell_reducer(spells, 'min')}")
69+ print(f"Empty: {spell_reducer([], 'add')}")
70+
71+ print("\nTesting partial enchanter...")
72+ enchants = partial_enchanter(base_enchant)
73+ print(enchants["fire"]("Sword"))
74+ print(enchants["ice"]("Shield"))
75+
76+ print("\nTesting memoized fibonacci...")
77+ print(f"fib(0): {memoized_fibonacci(0)}")
78+ print(f"Cache info: {memoized_fibonacci.cache_info()}")
79+ print(f"fib(1): {memoized_fibonacci(1)}")
80+ print(f"Cache info: {memoized_fibonacci.cache_info()}")
81+ print(f"fib(10): {memoized_fibonacci(10)}")
82+ print(f"Cache info: {memoized_fibonacci.cache_info()}")
83+ print(f"fib(15): {memoized_fibonacci(15)}")
84+ print(f"Cache info: {memoized_fibonacci.cache_info()}")
85+
86+
87+ print("\nTesting spell dispatcher...")
88+ dispatch = spell_dispatcher()
89+ print(dispatch(42))
90+ print(dispatch("fireball"))
91+ print(dispatch([10, "heal", 5]))
92+ print(dispatch(3.14))