]> Untitled Git - axy/ft/python03.git/commitdiff
Fixes and stuff
author= <=>
Mon, 12 Jan 2026 12:26:10 +0000 (13:26 +0100)
committer= <=>
Mon, 12 Jan 2026 12:26:10 +0000 (13:26 +0100)
ex0/ft_command_quest.py
ex1/ft_score_analytics.py
ex2/ft_coordinate_system.py
ex3/ft_achievement_tracker.py
ex4/ft_inventory_system.py
ex5/ft_data_stream.py
ex6/ft_analytics_dashboard.py

index eaf6b71fa052fb1ea02769e244e2b0f1c75ef349..852db63448755a7827918fef5b20ca3d5f36e428 100644 (file)
@@ -6,7 +6,7 @@ Master command-line communication and sys.argv
 import sys
 
 
-def main():
+def main() -> None:
     """Process and display command-line arguments."""
     print("=== Command Quest ===")
     print(f"Program name: {sys.argv[0]}")
index a5a89593181894061dc08a1086598d61cbabe37a..c60aac74550dddef3e370a892013894d6828a0c0 100644 (file)
@@ -6,7 +6,7 @@ Master lists by analyzing player scores
 import sys
 
 
-def main():
+def main() -> None:
     """Analyze player scores from command-line arguments."""
     print("=== Player Score Analytics ===")
 
@@ -17,11 +17,11 @@ def main():
         )
         return
 
-    scores = []
+    scores: list[int] = []
 
     for arg in sys.argv[1:]:
         try:
-            score = int(arg)
+            score: int = int(arg)
             scores.append(score)
         except ValueError:
             print(f"Error: '{arg}' is not a valid integer. Skipping.")
index 9044dd85474ffcce826667b662d37bdb557ce856..46a5bf088238b3bc6b5a85bd366a30e7d73b6776 100644 (file)
@@ -6,44 +6,56 @@ Master tuples and 3D coordinate systems
 import math
 
 
-def parse_coordinates(coord_string):
+def parse_coordinates(coord_string: str) -> tuple[float, float, float]:
     """Parse a coordinate string into a 3D tuple."""
     try:
-        parts = coord_string.split(",")
+        parts: list[str] = coord_string.split(",")
         if len(parts) != 3:
             raise ValueError("Coordinates must have 3 values")
-        x, y, z = float(parts[0]), float(parts[1]), float(parts[2])
+        x: float = float(parts[0])
+        y: float = float(parts[1])
+        z: float = float(parts[2])
         return (x, y, z)
     except (ValueError, AttributeError) as e:
         raise ValueError(f"Invalid coordinate format: {e}") from None
 
 
-def distance_3d(p1, p2):
+def distance_3d(
+    p1: tuple[float, float, float], p2: tuple[float, float, float]
+) -> float:
     """Calculate 3D Euclidean distance between two points."""
+    x1: float
+    y1: float
+    z1: float
     x1, y1, z1 = p1
+    x2: float
+    y2: float
+    z2: float
     x2, y2, z2 = p2
-    distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)
+    distance: float = math.sqrt(
+        (x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2
+    )
     return round(distance, 2)
 
 
-def main():
+def main() -> None:
     """Demonstrate 3D coordinate system using tuples."""
     print("=== Game Coordinate System ===")
     print()
 
     # Create and demonstrate a position
-    position1 = (10, 20, 5)
-    origin = (0, 0, 0)
+    position1: tuple[int, int, int] = (10, 20, 5)
+    origin: tuple[int, int, int] = (0, 0, 0)
 
     print(f"Position created: {position1}")
-    dist = distance_3d(origin, position1)
+    dist: float = distance_3d(origin, position1)
     print(f"Distance between {origin} and {position1}: {dist}")
     print()
 
     # Parse coordinates from string
     print('Parsing coordinates: "3,4,0"')
     try:
-        position2 = parse_coordinates("3,4,0")
+        position2: tuple[float, float, float] = parse_coordinates("3,4,0")
         print(f"Parsed position: {position2}")
         dist = distance_3d(origin, position2)
         print(f"Distance between {origin} and {position2}: {dist}")
@@ -64,6 +76,9 @@ def main():
 
     # Demonstrate tuple unpacking
     print("Unpacking demonstration:")
+    x: float
+    y: float
+    z: float
     x, y, z = position2
     print(f"Player at x={x}, y={y}, z={z}")
     print(f"Coordinates: X={x}, Y={y}, Z={z}")
index e74d602f2b0ebbd0a75af1d0ff8c0e7644c1103a..1ec4be674a651f8ea9dae638f4513ba7eb973d44 100644 (file)
@@ -4,14 +4,19 @@ Master sets for unique collections and analytics
 """
 
 
-def main():
+def main() -> None:
     """Demonstrate achievement tracking using sets."""
     print("=== Achievement Tracker System ===")
 
     # Create player achievements
-    alice = {"first_kill", "level_10", "treasure_hunter", "speed_demon"}
-    bob = {"first_kill", "level_10", "boss_slayer", "collector"}
-    charlie = {
+    alice: set[str] = {
+        "first_kill",
+        "level_10",
+        "treasure_hunter",
+        "speed_demon",
+    }
+    bob: set[str] = {"first_kill", "level_10", "boss_slayer", "collector"}
+    charlie: set[str] = {
         "level_10",
         "treasure_hunter",
         "boss_slayer",
@@ -27,33 +32,33 @@ def main():
     print("=== Achievement Analytics ===")
 
     # All unique achievements
-    all_achievements = alice | bob | charlie
+    all_achievements: set[str] = alice | bob | charlie
     print(f"All unique achievements: {all_achievements}")
     print(f"Total unique achievements: {len(all_achievements)}")
 
     # Common achievements across all players
-    common_achievements = alice & bob & charlie
+    common_achievements: set[str] = alice & bob & charlie
     print(f"Common to all players: {common_achievements}")
 
     # Rare achievements (in only 1 player)
-    achievement_counts = {}
+    achievement_counts: dict[str, int] = {}
     for achievement in all_achievements:
-        count = sum(
+        count: int = sum(
             1
             for player_set in [alice, bob, charlie]
             if achievement in player_set
         )
         achievement_counts[achievement] = count
 
-    rare_achievements = {
+    rare_achievements: set[str] = {
         ach for ach, count in achievement_counts.items() if count == 1
     }
     print(f"Rare achievements (1 player): {rare_achievements}")
 
     # Pairwise comparisons
-    alice_bob_common = alice & bob
-    alice_unique = alice - bob - charlie
-    bob_unique = bob - alice - charlie
+    alice_bob_common: set[str] = alice & bob
+    alice_unique: set[str] = alice - bob - charlie
+    bob_unique: set[str] = bob - alice - charlie
 
     print(f"Alice vs Bob common: {alice_bob_common}")
     print(f"Alice unique: {alice_unique}")
index b231f6111aa5386c6e65b2a25bb9b0ca6bac77ee..cf8ed1d5c75f82c6a97bc216a9dc4aac0651eb66 100644 (file)
@@ -3,13 +3,19 @@ Exercise 4: Inventory Master
 Master dictionaries for complex data storage and management
 """
 
+from typing import TypeAlias
 
-def main():
+
+ItemData: TypeAlias = dict[str, str | int]
+InventoryDict: TypeAlias = dict[str, ItemData]
+
+
+def main() -> None:
     """Demonstrate player inventory management using dictionaries."""
     print("=== Player Inventory System ===")
 
     # Create player inventories
-    alice_inventory = {
+    alice_inventory: InventoryDict = {
         "sword": {
             "type": "weapon",
             "rarity": "rare",
@@ -30,7 +36,7 @@ def main():
         },
     }
 
-    bob_inventory = {
+    bob_inventory: InventoryDict = {
         "potion": {
             "type": "consumable",
             "rarity": "common",
@@ -47,16 +53,16 @@ def main():
 
     # Display Alice's inventory
     print("=== Alice's Inventory ===")
-    alice_total_value = 0
-    alice_item_count = 0
-    alice_categories = {}
+    alice_total_value: int = 0
+    alice_item_count: int = 0
+    alice_categories: dict[str, int] = {}
 
     for item_name, item_data in alice_inventory.items():
-        quantity = item_data["quantity"]
-        item_type = item_data["type"]
-        rarity = item_data["rarity"]
-        value_each = item_data["value"]
-        total_value = quantity * value_each
+        quantity: int = item_data["quantity"]
+        item_type: str = item_data["type"]
+        rarity: str = item_data["rarity"]
+        value_each: int = item_data["value"]
+        total_value: int = quantity * value_each
 
         print(
             f"{item_name} ({item_type}, {rarity}): {quantity}x @ "
@@ -74,7 +80,7 @@ def main():
     print(f"Inventory value: {alice_total_value} gold")
     print(f"Item count: {alice_item_count} items")
 
-    categories_str = ", ".join(
+    categories_str: str = ", ".join(
         f"{cat}({qty})" for cat, qty in alice_categories.items()
     )
     print(f"Categories: {categories_str}")
@@ -97,7 +103,7 @@ def main():
     print("\n=== Inventory Analytics ===")
 
     # Most valuable player
-    bob_total_value = 0
+    bob_total_value: int = 0
     for item_data in bob_inventory.values():
         bob_total_value += item_data["quantity"] * item_data["value"]
 
@@ -107,7 +113,7 @@ def main():
         print(f"Most valuable player: Bob ({bob_total_value} gold)")
 
     # Most items
-    bob_item_count = sum(
+    bob_item_count: int = sum(
         item_data["quantity"] for item_data in bob_inventory.values()
     )
     if alice_item_count > bob_item_count:
@@ -116,13 +122,13 @@ def main():
         print(f"Most items: Bob ({bob_item_count} items)")
 
     # Rarest items
-    all_items = {}
+    all_items: dict[str, str] = {}
     for inventory in [alice_inventory, bob_inventory]:
         for item_name, item_data in inventory.items():
             if item_data["rarity"] == "rare":
                 all_items[item_name] = item_data["rarity"]
 
-    rare_items = list(all_items.keys())
+    rare_items: list[str] = list(all_items.keys())
     print(f"Rarest items: {', '.join(rare_items)}")
 
 
index f95ce085748a6128ab08e0b5cc2d1b3dd9fda6a8..b3565a004cfb886609da87cc705fae251d08d57a 100644 (file)
@@ -4,9 +4,9 @@ Master generators for memory-efficient data streaming
 """
 
 
-def game_event_stream(count):
+def game_event_stream(count: int):
     """Generate game events as a stream."""
-    events = [
+    events: list[tuple[str, dict[str, str | int]]] = [
         ("kill", {"player": "alice", "level": 5}),
         ("treasure", {"player": "bob", "level": 12}),
         ("levelup", {"player": "charlie", "level": 8}),
@@ -19,25 +19,26 @@ def game_event_stream(count):
         yield (i + 1, event_type, data)
 
 
-def filter_high_level_players(stream, min_level):
+def filter_high_level_players(stream, min_level: int):
     """Filter events for high-level players."""
     for event_num, event_type, data in stream:
         if data.get("level", 0) >= min_level:
             yield (event_num, event_type, data)
 
 
-def fibonacci_generator(count):
+def fibonacci_generator(count: int):
     """Generate first n Fibonacci numbers."""
-    a, b = 0, 1
+    a: int = 0
+    b: int = 1
     for _ in range(count):
         yield a
         a, b = b, a + b
 
 
-def prime_generator(count):
+def prime_generator(count: int):
     """Generate first n prime numbers."""
 
-    def is_prime(n):
+    def is_prime(n: int) -> bool:
         if n < 2:
             return False
         if n == 2:
@@ -49,8 +50,8 @@ def prime_generator(count):
                 return False
         return True
 
-    found = 0
-    num = 2
+    found: int = 0
+    num: int = 2
     while found < count:
         if is_prime(num):
             yield num
@@ -58,7 +59,7 @@ def prime_generator(count):
         num += 1
 
 
-def main():
+def main() -> None:
     """Demonstrate data streaming using generators."""
     print("=== Game Data Stream Processor ===")
     print("Processing 1000 game events...")
@@ -66,8 +67,11 @@ def main():
     # Show first few events
     stream = game_event_stream(1000)
     for i in range(3):
+        event_num: int
+        event_type: str
+        data: dict[str, str | int]
         event_num, event_type, data = next(stream)
-        action = {
+        action: dict[str, str] = {
             "kill": "killed monster",
             "treasure": "found treasure",
             "levelup": "leveled up",
@@ -86,13 +90,15 @@ def main():
 
     # Count high-level players
     stream = game_event_stream(1000)
-    high_level_count = sum(1 for _ in filter_high_level_players(stream, 10))
+    high_level_count: int = sum(
+        1 for _ in filter_high_level_players(stream, 10)
+    )
     print(f"High-level players (10+): {high_level_count}")
 
     # Count specific event types
     stream = game_event_stream(1000)
-    treasure_count = 0
-    levelup_count = 0
+    treasure_count: int = 0
+    levelup_count: int = 0
     for _, event_type, _ in stream:
         if event_type == "treasure":
             treasure_count += 1
@@ -109,12 +115,12 @@ def main():
     # Generator demonstrations
     print("\n=== Generator Demonstration ===")
 
-    fib_list = list(fibonacci_generator(10))
-    fib_str = ", ".join(str(x) for x in fib_list)
+    fib_list: list[int] = list(fibonacci_generator(10))
+    fib_str: str = ", ".join(str(x) for x in fib_list)
     print(f"Fibonacci sequence (first 10): {fib_str}")
 
-    primes_list = list(prime_generator(5))
-    primes_str = ", ".join(str(x) for x in primes_list)
+    primes_list: list[int] = list(prime_generator(5))
+    primes_str: str = ", ".join(str(x) for x in primes_list)
     print(f"Prime numbers (first 5): {primes_str}")
 
 
index a99ade0c63c63c1b0afb1b8f5595bd7f80735dd5..d7bab6bbec284a73c14f5a750d067a2fb7a3ea7b 100644 (file)
@@ -4,15 +4,15 @@ Master comprehensions for elegant data transformation
 """
 
 
-def main():
+def main() -> None:
     """Demonstrate comprehensions for data analytics."""
     print("=== Game Analytics Dashboard ===")
     print()
 
     # Sample data
-    players = ["alice", "bob", "charlie", "diana"]
-    scores = [2300, 1800, 2150, 2050]
-    achievements_data = {
+    players: list[str] = ["alice", "bob", "charlie", "diana"]
+    scores: list[int] = [2300, 1800, 2150, 2050]
+    achievements_data: dict[str, list[str]] = {
         "alice": [
             "first_kill",
             "level_10",
@@ -35,17 +35,17 @@ def main():
     print("\n=== List Comprehension Examples ===")
 
     # High scorers (>2000)
-    high_scorers = [
+    high_scorers: list[str] = [
         player for player, score in zip(players, scores) if score > 2000
     ]
     print(f"High scorers (>2000): {high_scorers}")
 
     # Scores doubled
-    scores_doubled = [score * 2 for score in scores]
+    scores_doubled: list[int] = [score * 2 for score in scores]
     print(f"Scores doubled: {scores_doubled}")
 
     # Active players (those with achievements)
-    active_players = [
+    active_players: list[str] = [
         player for player in players if player in achievements_data
     ]
     print(f"Active players: {active_players}")
@@ -55,11 +55,13 @@ def main():
     print("\n=== Dict Comprehension Examples ===")
 
     # Player scores mapping
-    player_scores = {player: score for player, score in zip(players, scores)}
+    player_scores: dict[str, int] = {
+        player: score for player, score in zip(players, scores)
+    }
     print(f"Player scores: {player_scores}")
 
     # Score categories
-    score_categories = {
+    score_categories: dict[str, int] = {
         "high": sum(1 for score in scores if score > 2200),
         "medium": sum(1 for score in scores if 1900 <= score <= 2200),
         "low": sum(1 for score in scores if score < 1900),
@@ -67,7 +69,7 @@ def main():
     print(f"Score categories: {score_categories}")
 
     # Achievement counts
-    achievement_counts = {
+    achievement_counts: dict[str, int] = {
         player: len(achievements)
         for player, achievements in achievements_data.items()
     }
@@ -78,11 +80,11 @@ def main():
     print("\n=== Set Comprehension Examples ===")
 
     # Unique players
-    unique_players = {player for player in players}
+    unique_players: set[str] = {player for player in players}
     print(f"Unique players: {unique_players}")
 
     # All unique achievements
-    unique_achievements = {
+    unique_achievements: set[str] = {
         achievement
         for achievements in achievements_data.values()
         for achievement in achievements
@@ -90,8 +92,8 @@ def main():
     print(f"Unique achievements: {unique_achievements}")
 
     # Active regions (simulated)
-    regions = ["north", "east", "central", "north", "east"]
-    active_regions = {region for region in regions}
+    regions: list[str] = ["north", "east", "central", "north", "east"]
+    active_regions: set[str] = {region for region in regions}
     print(f"Active regions: {active_regions}")
     print()
 
@@ -99,21 +101,21 @@ def main():
     print("\n=== Combined Analysis ===")
 
     # Total unique players
-    total_players = len(unique_players)
+    total_players: int = len(unique_players)
     print(f"Total players: {total_players}")
 
     # Total unique achievements
-    total_achievements = len(unique_achievements)
+    total_achievements: int = len(unique_achievements)
     print(f"Total unique achievements: {total_achievements}")
 
     # Average score
-    average_score = sum(scores) / len(scores)
+    average_score: float = sum(scores) / len(scores)
     print(f"Average score: {average_score}")
 
     # Top performer
-    top_player = max(player_scores, key=player_scores.get)
-    top_score = player_scores[top_player]
-    top_achievements = achievement_counts[top_player]
+    top_player: str = max(player_scores, key=player_scores.get)
+    top_score: int = player_scores[top_player]
+    top_achievements: int = achievement_counts[top_player]
     print(
         f"Top performer: {top_player} ({top_score} points, "
         f"{top_achievements} achievements)"