import sys
-def main():
+def main() -> None:
"""Process and display command-line arguments."""
print("=== Command Quest ===")
print(f"Program name: {sys.argv[0]}")
import sys
-def main():
+def main() -> None:
"""Analyze player scores from command-line arguments."""
print("=== Player Score Analytics ===")
)
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.")
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}")
# 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}")
"""
-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",
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}")
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",
},
}
- bob_inventory = {
+ bob_inventory: InventoryDict = {
"potion": {
"type": "consumable",
"rarity": "common",
# 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 @ "
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}")
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"]
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:
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)}")
"""
-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}),
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:
return False
return True
- found = 0
- num = 2
+ found: int = 0
+ num: int = 2
while found < count:
if is_prime(num):
yield num
num += 1
-def main():
+def main() -> None:
"""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: 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",
# 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
# 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}")
"""
-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",
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}")
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),
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()
}
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
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()
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)"