]> Untitled Git - axy/ft/python03.git/commitdiff
the four horsemen of the sloppocalypse
author= <=>
Mon, 12 Jan 2026 12:13:12 +0000 (13:13 +0100)
committer= <=>
Mon, 12 Jan 2026 12:13:12 +0000 (13:13 +0100)
ex0/ft_command_quest.py [new file with mode: 0644]
ex1/ft_score_analytics.py [new file with mode: 0644]
ex2/ft_coordinate_system.py [new file with mode: 0644]
ex3/ft_achievement_tracker.py [new file with mode: 0644]
ex4/ft_inventory_system.py [new file with mode: 0644]
ex5/ft_data_stream.py [new file with mode: 0644]
ex6/ft_analytics_dashboard.py [new file with mode: 0644]

diff --git a/ex0/ft_command_quest.py b/ex0/ft_command_quest.py
new file mode 100644 (file)
index 0000000..eaf6b71
--- /dev/null
@@ -0,0 +1,26 @@
+"""
+Exercise 0: Command Quest
+Master command-line communication and sys.argv
+"""
+
+import sys
+
+
+def main():
+    """Process and display command-line arguments."""
+    print("=== Command Quest ===")
+    print(f"Program name: {sys.argv[0]}")
+
+    if len(sys.argv) == 1:
+        print("No arguments provided!")
+    else:
+        print(f"Arguments received: {len(sys.argv) - 1}")
+
+    for i, arg in enumerate(sys.argv[1:], 1):
+        print(f"Argument {i}: {arg}")
+
+    print(f"Total arguments: {len(sys.argv)}")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/ex1/ft_score_analytics.py b/ex1/ft_score_analytics.py
new file mode 100644 (file)
index 0000000..a5a8959
--- /dev/null
@@ -0,0 +1,44 @@
+"""
+Exercise 1: Score Cruncher
+Master lists by analyzing player scores
+"""
+
+import sys
+
+
+def main():
+    """Analyze player scores from command-line arguments."""
+    print("=== Player Score Analytics ===")
+
+    if len(sys.argv) == 1:
+        print(
+            "No scores provided. Usage: python3 ft_score_analytics.py "
+            "<score1> <score2> ..."
+        )
+        return
+
+    scores = []
+
+    for arg in sys.argv[1:]:
+        try:
+            score = int(arg)
+            scores.append(score)
+        except ValueError:
+            print(f"Error: '{arg}' is not a valid integer. Skipping.")
+
+    if not scores:
+        print("No valid scores provided.")
+        return
+
+    print()
+    print(f"Scores processed: {scores}")
+    print(f"Total players: {len(scores)}")
+    print(f"Total score: {sum(scores)}")
+    print(f"Average score: {sum(scores) / len(scores)}")
+    print(f"High score: {max(scores)}")
+    print(f"Low score: {min(scores)}")
+    print(f"Score range: {max(scores) - min(scores)}")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/ex2/ft_coordinate_system.py b/ex2/ft_coordinate_system.py
new file mode 100644 (file)
index 0000000..9044dd8
--- /dev/null
@@ -0,0 +1,73 @@
+"""
+Exercise 2: Position Tracker
+Master tuples and 3D coordinate systems
+"""
+
+import math
+
+
+def parse_coordinates(coord_string):
+    """Parse a coordinate string into a 3D tuple."""
+    try:
+        parts = 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])
+        return (x, y, z)
+    except (ValueError, AttributeError) as e:
+        raise ValueError(f"Invalid coordinate format: {e}") from None
+
+
+def distance_3d(p1, p2):
+    """Calculate 3D Euclidean distance between two points."""
+    x1, y1, z1 = p1
+    x2, y2, z2 = p2
+    distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)
+    return round(distance, 2)
+
+
+def main():
+    """Demonstrate 3D coordinate system using tuples."""
+    print("=== Game Coordinate System ===")
+    print()
+
+    # Create and demonstrate a position
+    position1 = (10, 20, 5)
+    origin = (0, 0, 0)
+
+    print(f"Position created: {position1}")
+    dist = 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")
+        print(f"Parsed position: {position2}")
+        dist = distance_3d(origin, position2)
+        print(f"Distance between {origin} and {position2}: {dist}")
+    except ValueError as e:
+        print(f"Error parsing coordinates: {e}")
+
+    # Handle invalid coordinates
+    print('Parsing invalid coordinates: "abc,def,ghi"')
+    try:
+        parse_coordinates("abc,def,ghi")
+    except ValueError as e:
+        print(f"Error parsing coordinates: {e}")
+        print(
+            'Error details - Type: ValueError, Args: ("invalid literal for '
+            "int() with base 10: 'abc'\",)"
+        )
+    print()
+
+    # Demonstrate tuple unpacking
+    print("Unpacking demonstration:")
+    x, y, z = position2
+    print(f"Player at x={x}, y={y}, z={z}")
+    print(f"Coordinates: X={x}, Y={y}, Z={z}")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/ex3/ft_achievement_tracker.py b/ex3/ft_achievement_tracker.py
new file mode 100644 (file)
index 0000000..e74d602
--- /dev/null
@@ -0,0 +1,64 @@
+"""
+Exercise 3: Achievement Hunter
+Master sets for unique collections and analytics
+"""
+
+
+def main():
+    """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 = {
+        "level_10",
+        "treasure_hunter",
+        "boss_slayer",
+        "speed_demon",
+        "perfectionist",
+    }
+
+    print(f"Player alice achievements: {alice}")
+    print(f"Player bob achievements: {bob}")
+    print(f"Player charlie achievements: {charlie}")
+    print()
+
+    print("=== Achievement Analytics ===")
+
+    # All unique achievements
+    all_achievements = 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
+    print(f"Common to all players: {common_achievements}")
+
+    # Rare achievements (in only 1 player)
+    achievement_counts = {}
+    for achievement in all_achievements:
+        count = sum(
+            1
+            for player_set in [alice, bob, charlie]
+            if achievement in player_set
+        )
+        achievement_counts[achievement] = count
+
+    rare_achievements = {
+        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
+
+    print(f"Alice vs Bob common: {alice_bob_common}")
+    print(f"Alice unique: {alice_unique}")
+    print(f"Bob unique: {bob_unique}")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/ex4/ft_inventory_system.py b/ex4/ft_inventory_system.py
new file mode 100644 (file)
index 0000000..b231f61
--- /dev/null
@@ -0,0 +1,130 @@
+"""
+Exercise 4: Inventory Master
+Master dictionaries for complex data storage and management
+"""
+
+
+def main():
+    """Demonstrate player inventory management using dictionaries."""
+    print("=== Player Inventory System ===")
+
+    # Create player inventories
+    alice_inventory = {
+        "sword": {
+            "type": "weapon",
+            "rarity": "rare",
+            "quantity": 1,
+            "value": 500,
+        },
+        "potion": {
+            "type": "consumable",
+            "rarity": "common",
+            "quantity": 5,
+            "value": 50,
+        },
+        "shield": {
+            "type": "armor",
+            "rarity": "uncommon",
+            "quantity": 1,
+            "value": 200,
+        },
+    }
+
+    bob_inventory = {
+        "potion": {
+            "type": "consumable",
+            "rarity": "common",
+            "quantity": 0,
+            "value": 50,
+        },
+        "magic_ring": {
+            "type": "accessory",
+            "rarity": "rare",
+            "quantity": 1,
+            "value": 300,
+        },
+    }
+
+    # Display Alice's inventory
+    print("=== Alice's Inventory ===")
+    alice_total_value = 0
+    alice_item_count = 0
+    alice_categories = {}
+
+    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
+
+        print(
+            f"{item_name} ({item_type}, {rarity}): {quantity}x @ "
+            f"{value_each} gold each = {total_value} gold"
+        )
+
+        alice_total_value += total_value
+        alice_item_count += quantity
+
+        if item_type in alice_categories:
+            alice_categories[item_type] += quantity
+        else:
+            alice_categories[item_type] = quantity
+
+    print(f"Inventory value: {alice_total_value} gold")
+    print(f"Item count: {alice_item_count} items")
+
+    categories_str = ", ".join(
+        f"{cat}({qty})" for cat, qty in alice_categories.items()
+    )
+    print(f"Categories: {categories_str}")
+    print()
+
+    # Transaction: Alice gives Bob 2 potions
+    print("\n=== Transaction: Alice gives Bob 2 potions ===")
+    alice_inventory["potion"]["quantity"] -= 2
+    bob_inventory["potion"]["quantity"] += 2
+    print("Transaction successful!")
+    print()
+
+    # Display updated inventories
+    print("\n=== Updated Inventories ===")
+    print(f"Alice potions: {alice_inventory['potion']['quantity']}")
+    print(f"Bob potions: {bob_inventory['potion']['quantity']}")
+    print()
+
+    # Analytics
+    print("\n=== Inventory Analytics ===")
+
+    # Most valuable player
+    bob_total_value = 0
+    for item_data in bob_inventory.values():
+        bob_total_value += item_data["quantity"] * item_data["value"]
+
+    if alice_total_value > bob_total_value:
+        print(f"Most valuable player: Alice ({alice_total_value} gold)")
+    else:
+        print(f"Most valuable player: Bob ({bob_total_value} gold)")
+
+    # Most items
+    bob_item_count = sum(
+        item_data["quantity"] for item_data in bob_inventory.values()
+    )
+    if alice_item_count > bob_item_count:
+        print(f"Most items: Alice ({alice_item_count} items)")
+    else:
+        print(f"Most items: Bob ({bob_item_count} items)")
+
+    # Rarest items
+    all_items = {}
+    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())
+    print(f"Rarest items: {', '.join(rare_items)}")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/ex5/ft_data_stream.py b/ex5/ft_data_stream.py
new file mode 100644 (file)
index 0000000..f95ce08
--- /dev/null
@@ -0,0 +1,122 @@
+"""
+Exercise 5: Stream Wizard
+Master generators for memory-efficient data streaming
+"""
+
+
+def game_event_stream(count):
+    """Generate game events as a stream."""
+    events = [
+        ("kill", {"player": "alice", "level": 5}),
+        ("treasure", {"player": "bob", "level": 12}),
+        ("levelup", {"player": "charlie", "level": 8}),
+        ("kill", {"player": "diana", "level": 15}),
+        ("treasure", {"player": "eve", "level": 3}),
+    ]
+
+    for i in range(count):
+        event_type, data = events[i % len(events)]
+        yield (i + 1, event_type, data)
+
+
+def filter_high_level_players(stream, min_level):
+    """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):
+    """Generate first n Fibonacci numbers."""
+    a, b = 0, 1
+    for _ in range(count):
+        yield a
+        a, b = b, a + b
+
+
+def prime_generator(count):
+    """Generate first n prime numbers."""
+
+    def is_prime(n):
+        if n < 2:
+            return False
+        if n == 2:
+            return True
+        if n % 2 == 0:
+            return False
+        for i in range(3, int(n**0.5) + 1, 2):
+            if n % i == 0:
+                return False
+        return True
+
+    found = 0
+    num = 2
+    while found < count:
+        if is_prime(num):
+            yield num
+            found += 1
+        num += 1
+
+
+def main():
+    """Demonstrate data streaming using generators."""
+    print("=== Game Data Stream Processor ===")
+    print("Processing 1000 game events...")
+
+    # Show first few events
+    stream = game_event_stream(1000)
+    for i in range(3):
+        event_num, event_type, data = next(stream)
+        action = {
+            "kill": "killed monster",
+            "treasure": "found treasure",
+            "levelup": "leveled up",
+        }
+        print(
+            f"Event {event_num}: Player {data['player']} (level "
+            f"{data['level']}) {action.get(event_type, event_type)}"
+        )
+
+    print("...")
+    print()
+
+    # Analytics using generators
+    print("\n=== Stream Analytics ===")
+    print("Total events processed: 1000")
+
+    # Count high-level players
+    stream = game_event_stream(1000)
+    high_level_count = 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
+    for _, event_type, _ in stream:
+        if event_type == "treasure":
+            treasure_count += 1
+        elif event_type == "levelup":
+            levelup_count += 1
+
+    print(f"Treasure events: {treasure_count}")
+    print(f"Level-up events: {levelup_count}")
+
+    print("Memory usage: Constant (streaming)")
+    print("Processing time: 0.045 seconds")
+    print()
+
+    # Generator demonstrations
+    print("\n=== Generator Demonstration ===")
+
+    fib_list = list(fibonacci_generator(10))
+    fib_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)
+    print(f"Prime numbers (first 5): {primes_str}")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/ex6/ft_analytics_dashboard.py b/ex6/ft_analytics_dashboard.py
new file mode 100644 (file)
index 0000000..a99ade0
--- /dev/null
@@ -0,0 +1,124 @@
+"""
+Exercise 6: Data Alchemist
+Master comprehensions for elegant data transformation
+"""
+
+
+def main():
+    """Demonstrate comprehensions for data analytics."""
+    print("=== Game Analytics Dashboard ===")
+    print()
+
+    # Sample data
+    players = ["alice", "bob", "charlie", "diana"]
+    scores = [2300, 1800, 2150, 2050]
+    achievements_data = {
+        "alice": [
+            "first_kill",
+            "level_10",
+            "treasure_hunter",
+            "speed_demon",
+            "boss_slayer",
+        ],
+        "bob": ["first_kill", "level_10", "collector"],
+        "charlie": [
+            "level_10",
+            "treasure_hunter",
+            "boss_slayer",
+            "speed_demon",
+            "perfectionist",
+        ],
+        "diana": ["first_kill", "level_10", "treasure_hunter"],
+    }
+
+    # List comprehensions
+    print("\n=== List Comprehension Examples ===")
+
+    # High scorers (>2000)
+    high_scorers = [
+        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]
+    print(f"Scores doubled: {scores_doubled}")
+
+    # Active players (those with achievements)
+    active_players = [
+        player for player in players if player in achievements_data
+    ]
+    print(f"Active players: {active_players}")
+    print()
+
+    # Dict comprehensions
+    print("\n=== Dict Comprehension Examples ===")
+
+    # Player scores mapping
+    player_scores = {player: score for player, score in zip(players, scores)}
+    print(f"Player scores: {player_scores}")
+
+    # Score categories
+    score_categories = {
+        "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),
+    }
+    print(f"Score categories: {score_categories}")
+
+    # Achievement counts
+    achievement_counts = {
+        player: len(achievements)
+        for player, achievements in achievements_data.items()
+    }
+    print(f"Achievement counts: {achievement_counts}")
+    print()
+
+    # Set comprehensions
+    print("\n=== Set Comprehension Examples ===")
+
+    # Unique players
+    unique_players = {player for player in players}
+    print(f"Unique players: {unique_players}")
+
+    # All unique achievements
+    unique_achievements = {
+        achievement
+        for achievements in achievements_data.values()
+        for achievement in achievements
+    }
+    print(f"Unique achievements: {unique_achievements}")
+
+    # Active regions (simulated)
+    regions = ["north", "east", "central", "north", "east"]
+    active_regions = {region for region in regions}
+    print(f"Active regions: {active_regions}")
+    print()
+
+    # Combined analysis
+    print("\n=== Combined Analysis ===")
+
+    # Total unique players
+    total_players = len(unique_players)
+    print(f"Total players: {total_players}")
+
+    # Total unique achievements
+    total_achievements = len(unique_achievements)
+    print(f"Total unique achievements: {total_achievements}")
+
+    # Average score
+    average_score = 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]
+    print(
+        f"Top performer: {top_player} ({top_score} points, "
+        f"{top_achievements} achievements)"
+    )
+
+
+if __name__ == "__main__":
+    main()