Skip to content

Commit 7427120

Browse files
committed
Complete enums exercise
1 parent f52f136 commit 7427120

1 file changed

Lines changed: 109 additions & 0 deletions

File tree

‎sprint5-prep-exercises/enums.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
from dataclasses import dataclass
2+
from enum import Enum
3+
import sys
4+
5+
6+
class OperatingSystem(Enum):
7+
MACOS = "macOS"
8+
ARCH = "Arch Linux"
9+
UBUNTU = "Ubuntu"
10+
11+
12+
@dataclass(frozen=True)
13+
class Person:
14+
name: str
15+
age: int
16+
preferred_operating_system: OperatingSystem
17+
18+
19+
@dataclass(frozen=True)
20+
class Laptop:
21+
id: int
22+
manufacturer: str
23+
model: str
24+
screen_size_in_inches: float
25+
operating_system: OperatingSystem
26+
27+
28+
# 1. The library already has some laptops
29+
laptops = [
30+
Laptop(1, "Dell", "XPS", 13, OperatingSystem.ARCH),
31+
Laptop(2, "Dell", "XPS", 15, OperatingSystem.UBUNTU),
32+
Laptop(3, "Dell", "XPS", 15, OperatingSystem.UBUNTU),
33+
Laptop(4, "Apple", "MacBook", 13, OperatingSystem.MACOS),
34+
]
35+
36+
37+
# 2. Get the person's name
38+
name = input("Enter your name: ")
39+
40+
41+
# Get age as text, then convert it to int immediately
42+
age_input = input("Enter your age: ")
43+
44+
try:
45+
age = int(age_input)
46+
except ValueError:
47+
print("Error: age must be a whole number.", file=sys.stderr)
48+
sys.exit(1)
49+
50+
51+
# Get operating system as text, then convert it to an enum immediately
52+
os_input = input(
53+
"Enter your preferred operating system "
54+
"(Ubuntu, Arch Linux, macOS): "
55+
)
56+
57+
try:
58+
preferred_os = OperatingSystem(os_input)
59+
except ValueError:
60+
print(
61+
"Error: operating system must be Ubuntu, Arch Linux, or macOS.",
62+
file=sys.stderr,
63+
)
64+
sys.exit(1)
65+
66+
67+
# Now we have correctly typed data, so create the Person
68+
person = Person(
69+
name=name,
70+
age=age,
71+
preferred_operating_system=preferred_os,
72+
)
73+
74+
75+
# 3. Count laptops with the person's preferred operating system
76+
preferred_count = 0
77+
78+
for laptop in laptops:
79+
if laptop.operating_system == person.preferred_operating_system:
80+
preferred_count += 1
81+
82+
83+
print(
84+
f"The library has {preferred_count} laptop(s) "
85+
f"with {person.preferred_operating_system.value}."
86+
)
87+
88+
89+
# 4. Check whether another operating system has more laptops
90+
for operating_system in OperatingSystem:
91+
92+
# Don't compare their preferred OS with itself
93+
if operating_system == person.preferred_operating_system:
94+
continue
95+
96+
count = 0
97+
98+
for laptop in laptops:
99+
if laptop.operating_system == operating_system:
100+
count += 1
101+
102+
if count > preferred_count:
103+
print(
104+
f"If you are willing to use {operating_system.value}, "
105+
f"you are more likely to get a laptop because "
106+
f"the library has {count} available."
107+
)
108+
109+

0 commit comments

Comments
 (0)