59f75c8module-03(ex{0..6}): cleanup entire module
7 files changed, +107, -198
@@ -5,23 +5,16 @@ def main() -> None:
5 5 print("=== Command Quest ===")
6 6
7 7 print(f"Program name: {sys.argv[0]}")
8 -
9 8 argc = len(sys.argv) - 1
10 -
11 9 if argc == 0:
1210 print("No arguments provided!")
13 -
1411 else:
15 - print(f"Arguments received: {argc}")
16 -
17 - index = 0
18 - for arg in sys.argv:
19 - if index == 0:
20 - index += 1
21 - continue
22 - print(f"Argument {index}: {arg}")
23 - index += 1
24 - print(f"Total arguments: {len(sys.argv)}")
12+ print("Arguments received:", argc)
13+ i = 1
14+ for arg in sys.argv[1:]:
15+ print(f"Argument {i}: {arg}")
16+ i += 1
17+ print("Total arguments:", len(sys.argv))
2518
2619
2720 if __name__ == "__main__":
+15, -25
@@ -3,40 +3,30 @@ import sys
3 3
4 4 def main() -> None:
5 5 print("=== Player Score Analytics ===")
6 -
7 6 scores = []
8 -
9 - first_arg = True
10 -
11 - for arg in sys.argv:
12 - if first_arg:
13 - first_arg = False
14 - continue
15 -
7+ for arg in sys.argv[1:]:
16 8 try:
17 9 scores.append(int(arg))
1810 except Exception:
19 - print(f"Invalid parameter: '{arg}'")
20 -
11+ print("Invalid parameter:", arg)
2112 if len(scores) == 0:
2213 print(
2314 "No scores provided."
2415 "Usage: python3 ft_score_analytics.py <score1> <score2> ..."
2516 )
26 - else:
27 - total = sum(scores)
28 - avg = total / len(scores)
29 - high = max(scores)
30 - low = min(scores)
31 - score_range = high - low
32 -
33 - print(f"Scores processed: {scores}")
34 - print(f"Total players: {len(scores)}")
35 - print(f"Total score: {total}")
36 - print(f"Average score: {avg}")
37 - print(f"High score: {high}")
38 - print(f"Low score: {low}")
39 - print(f"Score range: {score_range}")
17+ return
18+ total = sum(scores)
19+ avg = total / len(scores)
20+ high = max(scores)
21+ low = min(scores)
22+ score_range = high - low
23+ print("Scores processed:", scores)
24+ print("Total players:", len(scores))
25+ print("Total score:", total)
26+ print("Average score:", avg)
27+ print("High score:", high)
28+ print("Low score:", low)
29+ print("Score range:", score_range)
4030
4131
4232 if __name__ == "__main__":
@@ -4,76 +4,63 @@ import math
4 4 def get_player_pos() -> tuple[float, float, float] | None:
5 5 while True:
6 6 try:
7 - user_input = input(
7+ coordinates = input(
8 8 "Enter new coordinates as floats in format 'x,y,z': "
9 - )
10 -
9+ ).split(',')
1110 except KeyboardInterrupt:
1211 print("\nProgram interrupted by user.")
1312 return None
14 -
15 - coordinates = user_input.split(',')
16 -
1713 if len(coordinates) != 3:
1814 print("Invalid syntax")
1915 continue
20 -
2116 try:
22 - x = float(coordinates[0].strip())
23 - y = float(coordinates[1].strip())
24 - z = float(coordinates[2].strip())
25 -
26 - return (x, y, z)
27 -
17+ res = [float(coord.strip()) for coord in coordinates]
18+ return (res[0], res[1], res[2])
2819 except ValueError as error:
2920 invalid_input = ""
30 -
31 - for coordinate in coordinates:
21+ for coord in coordinates:
3222 try:
33 - float(coordinate.strip())
23+ float(coord.strip())
3424 except ValueError:
35 - invalid_input = coordinate.strip()
25+ invalid_input = coord.strip()
3626 break
37 -
3827 print(f"Error on parameter '{invalid_input}': {error}")
3928
4029
41 -def main() -> None:
42 - print("=== Game Coordinate System ===")
43 -
44 - print("Get a first set of coordinates")
45 - pos1 = get_player_pos()
30+def calc_dist(
31+ p1: tuple[float, float, float],
32+ p2: tuple[float, float, float]
33+) -> float:
34+ return math.sqrt(
35+ (p2[0] - p1[0]) ** 2 +
36+ (p2[1] - p1[1]) ** 2 +
37+ (p2[2] - p1[2]) ** 2
38+ )
4639
47 - if pos1 is None:
48 - return
4940
50 - print(f"Got a first tuple: {pos1}")
51 - print(f"It includes: X={pos1[0]}, Y={pos1[1]}, Z={pos1[2]}")
41+def print_point(p: tuple[float, float, float]) -> None:
42+ print("Got a first tuple:", p)
43+ print(f"It includes: X={p[0]}, Y={p[1]}, Z={p[2]}")
5244
53 - distance_center = math.sqrt(
54 - pos1[0] ** 2 +
55 - pos1[1] ** 2 +
56 - pos1[2] ** 2
57 - )
5845
59 - print(f"Distance to center: {distance_center:.4f}")
46+def main() -> None:
47+ print("=== Game Coordinate System ===")
6048
49+ print("Get a first set of coordinates")
50+ p1 = get_player_pos()
51+ if p1 is None:
52+ return
53+ print_point(p1)
54+ print(f"Distance to center: {calc_dist(p1, (0.0, 0.0, 0.0)):.4f}")
6155 print()
62 - print("Get a second set of coordinates")
63 - pos2 = get_player_pos()
6456
65 - if pos2 is None:
57+ print("Get a second set of coordinates")
58+ p2 = get_player_pos()
59+ if p2 is None:
6660 return
67 -
68 - distance_between = math.sqrt(
69 - (pos2[0] - pos1[0]) ** 2 +
70 - (pos2[1] - pos1[1]) ** 2 +
71 - (pos2[2] - pos1[2]) ** 2
72 - )
73 -
7461 print(
75 - f"Distance between the 2 sets of coordinates: "
76 - f"{distance_between:.4f}"
62+ "Distance between the 2 sets of coordinates: "
63+ f"{calc_dist(p1, p2):.4f}"
7764 )
7865
7966
@@ -1,85 +1,65 @@
1 1 import random
2 2
3 3
4 -def main() -> None:
5 - def gen_player_achievements():
6 - all_achievements = [
7 - "First Steps",
8 - "Treasure Hunter",
9 - "Boss Slayer",
10 - "Master Explorer",
11 - "Crafting Genius",
12 - "Untouchable",
13 - "World Savior",
14 - "Sharp Mind",
15 - "Collector Supreme",
16 - "Speed Runner",
17 - "Strategist",
18 - "Unstoppable",
19 - "Hidden Path Finder",
20 - "Survivor"
21 - ]
22 -
23 - amount = random.randint(5, 9)
24 -
25 - achievements = set()
4+def gen_player_achievements(achs: list[str]) -> set[str]:
5+ return set(random.sample(achs, random.randint(5, len(achs))))
26 6
27 - while len(achievements) < amount:
28 - achievement = random.choice(all_achievements)
29 - achievements.add(achievement)
30 7
31 - return achievements
8+def main() -> None:
9+ achievments = [
10+ "First Steps",
11+ "Treasure Hunter",
12+ "Boss Slayer",
13+ "Master Explorer",
14+ "Crafting Genius",
15+ "Untouchable",
16+ "World Savior",
17+ "Sharp Mind",
18+ "Collector Supreme",
19+ "Speed Runner",
20+ "Strategist",
21+ "Unstoppable",
22+ "Hidden Path Finder",
23+ "Survivor"
24+ ]
3225
3326 print("=== Achievement Tracker System ===\n")
3427
35 - alice = gen_player_achievements()
36 - bob = gen_player_achievements()
37 - charlie = gen_player_achievements()
38 - dylan = gen_player_achievements()
39 -
40 - player_names = ("Alice", "Bob", "Charlie", "Dylan")
41 - player_sets = (alice, bob, charlie, dylan)
42 -
43 - for i in [0, 1, 2, 3]:
44 - print(f"Player {player_names[i]}: {player_sets[i]}")
45 -
28+ players = {
29+ "Alice": gen_player_achievements(achievments),
30+ "Bob": gen_player_achievements(achievments),
31+ "Charlie": gen_player_achievements(achievments),
32+ "Dylan": gen_player_achievements(achievments)
33+ }
34+ player_sets = list(players.values())
35+ for name in players:
36+ print(f"Player {name}: {players[name]}")
4637 print()
38+
4739 # distinct
4840 all_distinct: set[str] = set()
49 -
50 - for achievements in player_sets:
51 - all_distinct = all_distinct.union(achievements)
52 -
41+ for achs in players.values():
42+ all_distinct = all_distinct.union(achs)
5343 print(f"All distinct achievements: {all_distinct}")
54 -
5544 print()
56 - # common
57 - common = player_sets[0]
58 -
59 - for i in [1, 2, 3]:
60 - common = common.intersection(player_sets[i])
61 -
62 - print(f"Common achievements: {common}")
6345
46+ # shared
47+ shared = set.intersection(*player_sets)
48+ print(f"Common achievements: {shared}")
6449 print()
65 - # unique
66 - for i in [0, 1, 2, 3]:
67 - others: set[str] = set()
68 -
69 - for j in [0, 1, 2, 3]:
70 - if i != j:
71 - others = others.union(player_sets[j])
72 -
73 - unique = player_sets[i].difference(others)
74 -
75 - print(f"Only {player_names[i]} has: {unique}")
7650
51+ # unique
52+ for name in players:
53+ unique = players[name].difference(
54+ *(players[other] for other in players if other != name)
55+ )
56+ print(f"Only {name} has: {unique}")
7757 print()
78 - # missing
79 - for i in [0, 1, 2, 3]:
80 - missing = all_distinct.difference(player_sets[i])
8158
82 - print(f"{player_names[i]} is missing: {missing}")
59+ # missing
60+ for name in players:
61+ missing = all_distinct.difference(players[name])
62+ print(f"{name} is missing: {missing}")
8363
8464
8565 if __name__ == "__main__":
@@ -5,77 +5,53 @@ def main() -> None:
5 5 print("=== Inventory System Analysis ===")
6 6
7 7 inventory: dict[str, int] = {}
8 -
9 - first = True
10 -
11 - for arg in sys.argv:
12 - if first:
13 - first = False
14 - continue
15 -
8+ for arg in sys.argv[1:]:
16 9 parameter = arg.split(":")
17 -
1810 if len(parameter) != 2:
1911 print(f"Error - invalid parameter '{arg}'")
2012 continue
21 -
2213 item = parameter[0]
23 - quantity_text = parameter[1]
24 -
14+ quantity_str = parameter[1]
2515 if item in inventory.keys():
2616 print(f"Redundant item '{item}' - discarding")
2717 continue
28 -
2918 try:
30 - quantity = int(quantity_text)
19+ quantity = int(quantity_str)
3120 except ValueError as error:
3221 print(f"Quantity error for '{item}': {error}")
3322 continue
34 -
3523 inventory.update({item: quantity})
3624
3725 print(f"Got inventory: {inventory}")
38 -
3926 item_list = list(inventory.keys())
40 -
4127 print(f"Item list: {item_list}")
42 -
4328 if len(item_list) == 0:
4429 print("No items in inventory.")
4530 else:
4631 total_quantity = sum(inventory.values())
47 -
4832 print(
4933 f"Total quantity of the {len(inventory)} items: "
5034 f"{total_quantity}"
5135 )
52 -
5336 for item in inventory.keys():
5437 percentage = (inventory[item] / total_quantity) * 100
55 -
5638 print(f"Item {item} represents {percentage:.1f}%")
57 -
5839 most_item = item_list[0]
5940 least_item = item_list[0]
60 -
6141 for item in item_list:
6242 if inventory[item] > inventory[most_item]:
6343 most_item = item
6444 if inventory[item] < inventory[least_item]:
6545 least_item = item
66 -
6746 print(
6847 f"Item most abundant: {most_item} "
6948 f"with quantity {inventory[most_item]}"
7049 )
71 -
7250 print(
7351 f"Item least abundant: "
7452 f"{least_item} with quantity {inventory[least_item]}"
7553 )
76 -
7754 inventory.update({"magic_item": 1})
78 -
7955 print(f"Updated inventory: {inventory}")
8056
8157
+3, -11
@@ -6,7 +6,6 @@ def gen_event() -> typing.Generator[tuple[str, str], None, None]:
6 6 players = ["alice", "bob", "charlie", "dylan"]
7 7 actions = ["run", "eat", "sleep", "grab",
8 8 "move", "climb", "swim", "release"]
9 -
10 9 while True:
1110 player = random.choice(players)
1211 action = random.choice(actions)
@@ -19,10 +18,6 @@ def consume_event(
1918 while len(events) > 0:
2019 index = random.randint(0, len(events) - 1)
2120 event = events.pop(index)
22 -
23 - print(f"Got event from list: {event}")
24 - print(f"Remains in list {events}")
25 -
2621 yield event
2722
2823
@@ -36,15 +31,12 @@ def main() -> None:
3631 print(f"Event {i}: Player {name} did action {action}")
3732
3833 event_list = []
39 - event_gen = gen_event()
40 -
4134 for i in range(10):
4235 event_list.append(next(event_gen))
43 -
4436 print(f"Built list of 10 events: {event_list}")
45 -
46 - for _ in consume_event(event_list):
47 - pass
37+ for event in consume_event(event_list):
38+ print(f"Got event from list: {event}")
39+ print(f"Remains in list {event_list}")
4840
4941
5042 if __name__ == "__main__":
@@ -8,29 +8,20 @@ def main() -> None:
8 8 'Alice', 'bob', 'Charlie', 'dylan',
9 9 'Emma', 'Gregory', 'john', 'kevin', 'Liam'
1010 ]
11 -
1211 print(f"Initial list of players: {players}")
13 -
1412 capitalized = [name.capitalize() for name in players]
15 -
1613 print(f"New list with all names capitalized: {capitalized}")
17 -
1814 capitalized_only = [name for name in players if name[0].isupper()]
19 - capitalized_only = [name.capitalize() for name in capitalized_only]
20 -
2115 print(f"New list of capitalized names only: {capitalized_only}")
2216
2317 scores = {name: random.randint(50, 1000) for name in capitalized}
24 -
2518 print(f"Score dict: {scores}")
26 -
2719 avg = sum(scores.values()) / len(scores)
28 -
2920 print(f"Score average is {avg:.1f}")
30 -
31 - high_scores = {name: score for name, score in
32 - scores.items() if score > avg}
33 -
21+ high_scores = {
22+ name: score for name, score in
23+ scores.items() if score > avg
24+ }
3425 print(f"High scores: {high_scores}")
3526
3627