1+ #import Python tools for structured data (dataclass), enumerations (Enum), and type hints (List, Dict)
2+ from dataclasses import dataclass
3+ from enum import Enum
4+ from typing import List , Dict , Tuple
5+ #Define a fixed set of operating systems as an enum to avoid typos and enforce valid values
6+ class OperatingSystem (Enum ):
7+ MACOS = "macOS"
8+ ARCH = "Arch Linux"
9+ UBUNTU = "Ubuntu"
10+ #Rep a person with a name, age, and ordered preferences of operating systems(immutable)
11+ @dataclass (frozen = True )
12+ class Person :
13+ name : str
14+ age : int
15+ preferred_operating_system : tuple [OperatingSystem , ...]
16+
17+ #Repr a laptop with identifying info, screen size, and its operating system
18+ @dataclass (frozen = True )
19+ class Laptop :
20+ id : int
21+ manufacturer : str
22+ model : str
23+ screen_size_in_inches : float
24+ operating_system : OperatingSystem
25+
26+ #Main function to assign exactly one laptop per person while minimizing “sadness”
27+ def allocate_laptops (people : List [Person ], laptops : List [Laptop ]) -> Dict [Person , Laptop ]:
28+ sadness_list : List [Tuple [int , Person , Laptop ]] = []
29+ #Compute sadness for each laptop for each person (0 = best match, 100 = not preferred)
30+ for person in people :
31+ for laptop in laptops :
32+ if laptop .operating_system in person .preferred_operating_system :
33+ sadness = person .preferred_operating_system .index (laptop .operating_system )
34+ else :
35+ sadness = 100
36+ sadness_list .append ((sadness , person , laptop ))
37+
38+ # Sort by sadness (lowest first)
39+ sadness_list .sort (key = lambda x : x [0 ])
40+ #Track assigned laptops and people to ensure uniqueness
41+ allocations : Dict [Person , Laptop ] = {}
42+ allocated_laptops = set ()
43+
44+ #Greedily allocate laptops to minimise sadness
45+ for sadness , person , laptop in sadness_list :
46+ if person not in allocations and laptop .id not in allocated_laptops :
47+ allocations [person ] = laptop
48+ allocated_laptops .add (laptop .id )
49+
50+ return allocations
51+
52+
53+
54+
55+
56+
57+ #example usage
58+ people = [
59+ Person ("Imran" , 22 , (OperatingSystem .UBUNTU , OperatingSystem .ARCH , OperatingSystem .MACOS )),
60+ Person ("Eliza" , 34 , (OperatingSystem .ARCH , OperatingSystem .UBUNTU )),
61+ ]
62+ laptops = [
63+ Laptop (1 , "Dell" , "XPS 13" , 13 , OperatingSystem .ARCH ),
64+ Laptop (2 , "Apple" , "MacBook" , 13 , OperatingSystem .MACOS ),
65+ Laptop (3 , "Dell" , "XPS 15" , 15 , OperatingSystem .UBUNTU ),
66+ ]
67+ allocations = allocate_laptops (people , laptops )
68+ for person , laptop in allocations .items ():
69+ print (f"{ person .name } gets { laptop .manufacturer } { laptop .model } ({ laptop .operating_system .value } )" )
0 commit comments