91 lines
2.8 kB
1from functools import reduce, partial, lru_cache, singledispatch
2from operator import add, mul
3from collections.abc import Callable
4
5
6def 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 return reduce(ops[operation], spells)
18
19
20def partial_enchanter(base_enchantment: Callable) -> dict[str, Callable]:
21 return {
22 "fire": partial(base_enchantment, power=50, element="fire"),
23 "ice": partial(base_enchantment, power=50, element="ice"),
24 "lightning": partial(base_enchantment, power=50, element="lightning"),
25 }
26
27
28@lru_cache(maxsize=None)
29def memoized_fibonacci(n: int) -> int:
30 if n <= 1:
31 return n
32 return memoized_fibonacci(n - 1) + memoized_fibonacci(n - 2)
33
34
35def spell_dispatcher() -> Callable:
36 @singledispatch
37 def dispatch(_) -> str:
38 return "Unknown spell type"
39
40 @dispatch.register(int)
41 def _(spell: int) -> str:
42 return f"Damage spell: {spell} damage"
43
44 @dispatch.register(str)
45 def _(spell: str) -> str:
46 return f"Enchantment: {spell}"
47
48 @dispatch.register(list)
49 def _(spell: list) -> str:
50 return f"Multi-cast: {len(spell)} spells"
51
52 return dispatch
53
54
55def base_enchant(power: int, element: str, target: str) -> str:
56 return (
57 f"{element.capitalize()} enchantment on {target} (power {power})"
58 )
59
60
61if __name__ == "__main__":
62 print("Testing spell reducer...")
63 spells = [10, 20, 30, 40]
64 print(f"Add: {spell_reducer(spells, 'add')}")
65 print(f"Multiply: {spell_reducer(spells, 'multiply')}")
66 print(f"Max: {spell_reducer(spells, 'max')}")
67 print(f"Min: {spell_reducer(spells, 'min')}")
68 print(f"Empty: {spell_reducer([], 'add')}")
69
70 print("\nTesting partial enchanter...")
71 enchants = partial_enchanter(base_enchant)
72 print(enchants["fire"](target="Sword"))
73 print(enchants["ice"](target="Shield"))
74 print(enchants["lightning"](target="Staff"))
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 print("\nTesting spell dispatcher...")
87 dispatch = spell_dispatcher()
88 print(dispatch(42))
89 print(dispatch("fireball"))
90 print(dispatch([10, "heal", 5]))
91 print(dispatch(3.14))