f51fe91module-10: add ex2
1 file changed, +61, -0
+61, -0
@@ -0,0 +1,61 @@
1+from collections.abc import Callable
2+
3+
4+def mage_counter() -> Callable:
5+ count = 0
6+ def counter() -> int:
7+ nonlocal count
8+ count += 1
9+ return count
10+ return counter
11+
12+
13+def spell_accumulator(initial_power: int) -> Callable:
14+ total = initial_power
15+ def accumulate(amount: int) -> int:
16+ nonlocal total
17+ total += amount
18+ return total
19+ return accumulate
20+
21+
22+def enchantment_factory(enchantment_type: str) -> Callable:
23+ def enchant(item_name: str) -> str:
24+ return f"{enchantment_type} {item_name}"
25+ return enchant
26+
27+
28+def memory_vault() -> dict[str, Callable]:
29+ vault: dict = {}
30+ def store(key: str, value: object) -> None:
31+ vault[key] = value
32+ def recall(key: str) -> object:
33+ return vault.get(key, "Memory not found")
34+ return {"store": store, "recall": recall}
35+
36+
37+if __name__ == "__main__":
38+ print("Testing mage counter...")
39+ counter_a = mage_counter()
40+ counter_b = mage_counter()
41+ print(f"counter_a call 1: {counter_a()}")
42+ print(f"counter_a call 2: {counter_a()}")
43+ print(f"counter_b call 1: {counter_b()}")
44+
45+ print("\nTesting spell accumulator...")
46+ acc = spell_accumulator(100)
47+ print(f"Base 100, add 20: {acc(20)}")
48+ print(f"Base 100, add 30: {acc(30)}")
49+
50+ print("\nTesting enchantment factory...")
51+ flaming = enchantment_factory("Flaming")
52+ frozen = enchantment_factory("Frozen")
53+ print(flaming("Sword"))
54+ print(frozen("Shield"))
55+
56+ print("\nTesting memory vault...")
57+ mv = memory_vault()
58+ mv["store"]("secret", 42)
59+ print("Store 'secret' = 42")
60+ print(f"Recall 'secret': {mv['recall']('secret')}")
61+ print(f"Recall 'unknown': {mv['recall']('unknown')}")