|
| 1 | +# ------------------------ |
| 2 | +# Q. Try changing the type annotation of Person.preferred_operating_system from str to List[str]. |
| 3 | + |
| 4 | +# Run mypy on the code. |
| 5 | + |
| 6 | +# It tells us different places that our code is now wrong, because we’re passing values of the wrong type. |
| 7 | + |
| 8 | +# We probably also want to rename our field - lists are plural. Rename the field to preferred_operating_systems. |
| 9 | + |
| 10 | +# Run mypy again. |
| 11 | + |
| 12 | +# Fix all of the places that mypy tells you need changing. Make sure the program works as you’d expect. |
| 13 | + |
| 14 | +# ------------------------ |
| 15 | + |
| 16 | +# A. |
| 17 | + |
| 18 | +from dataclasses import dataclass |
| 19 | +from typing import List |
| 20 | + |
| 21 | + |
| 22 | +@dataclass(frozen=True) |
| 23 | +class Person: |
| 24 | + name: str |
| 25 | + age: int |
| 26 | + preferred_operating_systems: List[str] |
| 27 | + |
| 28 | + |
| 29 | +@dataclass(frozen=True) |
| 30 | +class Laptop: |
| 31 | + id: int |
| 32 | + manufacturer: str |
| 33 | + model: str |
| 34 | + screen_size_in_inches: float |
| 35 | + operating_system: str |
| 36 | + |
| 37 | + |
| 38 | +def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]: |
| 39 | + possible_laptops: List[Laptop] = [] |
| 40 | + for laptop in laptops: |
| 41 | + for operating_system in person.preferred_operating_systems: |
| 42 | + |
| 43 | + if laptop.operating_system == operating_system: |
| 44 | + possible_laptops.append(laptop) |
| 45 | + return possible_laptops |
| 46 | + |
| 47 | + |
| 48 | +people = [ |
| 49 | + Person(name="Imran", age=22, preferred_operating_systems=[ |
| 50 | + "Ubuntu", "Arch Linux"]), |
| 51 | + Person(name="Eliza", age=34, preferred_operating_systems=[ |
| 52 | + "Arch Linux", "macOS"]), |
| 53 | +] |
| 54 | + |
| 55 | +laptops = [ |
| 56 | + Laptop(id=1, manufacturer="Dell", model="XPS", |
| 57 | + screen_size_in_inches=13, operating_system="Arch Linux"), |
| 58 | + Laptop(id=2, manufacturer="Dell", model="XPS", |
| 59 | + screen_size_in_inches=15, operating_system="Ubuntu"), |
| 60 | + Laptop(id=3, manufacturer="Dell", model="XPS", |
| 61 | + screen_size_in_inches=15, operating_system="ubuntu"), |
| 62 | + Laptop(id=4, manufacturer="Apple", model="macBook", |
| 63 | + screen_size_in_inches=13, operating_system="macOS"), |
| 64 | +] |
| 65 | + |
| 66 | +for person in people: |
| 67 | + possible_laptops = find_possible_laptops(laptops, person) |
| 68 | + print(f"Possible laptops for {person.name}: {possible_laptops}") |
0 commit comments