1+ # exercise
2+ # Write a program which:
3+
4+ # Already has a list of Laptops that a library has to lend out.
5+ # Accepts user input to create a new Person - it should use the input function to read a person’s name,
6+ # age, and preferred operating system.
7+ # Tells the user how many laptops the library has that have that operating system.
8+ # If there is an operating system that has more laptops available, tells the user that
9+ # if they’re willing to accept that operating system they’re more likely to get a laptop.
10+
11+ from dataclasses import dataclass
12+ from enum import Enum
13+ from typing import List
14+ import sys
15+
16+ class OperatingSystem (Enum ):
17+ MACOS = "macOS"
18+ ARCH = "Arch Linux"
19+ UBUNTU = "Ubuntu"
20+
21+ @dataclass (frozen = True )
22+ class Laptop :
23+ id : int
24+ manufacturer : str
25+ model : str
26+ screen_size_in_inches : float
27+ operating_system : OperatingSystem
28+
29+ laptops : List [Laptop ] = [
30+ Laptop (id = 1 , manufacturer = "Dell" , model = "XPS" , screen_size_in_inches = 13 , operating_system = OperatingSystem .ARCH ),
31+ Laptop (id = 2 , manufacturer = "Dell" , model = "XPS" , screen_size_in_inches = 15 , operating_system = OperatingSystem .UBUNTU ),
32+ Laptop (id = 3 , manufacturer = "Dell" , model = "XPS" , screen_size_in_inches = 15 , operating_system = OperatingSystem .UBUNTU ),
33+ Laptop (id = 4 , manufacturer = "Apple" , model = "macBook" , screen_size_in_inches = 13 , operating_system = OperatingSystem .MACOS ),
34+ ]
35+
36+ def convert_os (user_input : str ) -> OperatingSystem :
37+ for os_value in OperatingSystem :
38+ if user_input .lower () == os_value .value .lower ():
39+ return os_value
40+ print (f"Error: '{ user_input } ' is not a valid operating system." , file = sys .stderr )
41+ sys .exit (1 )
42+
43+ # Get user input
44+ name = input ("Enter your name: " ).strip ()
45+ age_input = input ("Enter your age: " ).strip ()
46+ if not age_input .isdigit ():
47+ print (f"Error: '{ age_input } ' age must be a number." , file = sys .stderr )
48+ sys .exit (1 )
49+ age = int (age_input )
50+
51+ os_input = input ("Enter your preferred operating system (macOS, Arch Linux, Ubuntu): " ).strip ()
52+ preferred_os = convert_os (os_input )
53+
54+ # Count laptops with the preferred operating system
55+ matching_laptops = [laptop for laptop in laptops if laptop .operating_system == preferred_os ]
56+ print (f"\n Hi { name } , there are { len (matching_laptops )} laptops available with { preferred_os .value } ." )
57+
58+ # Check if there are better laptops with a different operating system
59+ counts = {os : 0 for os in OperatingSystem }
60+ for laptop in laptops :
61+ counts [laptop .operating_system ] += 1
62+
63+ best_os = max (counts , key = counts .get )
64+ if best_os != preferred_os :
65+ print (f"if you’re willing to accept { best_os .value } you’re more likely to get a laptop, as there are { counts [best_os ]} available." )
0 commit comments