Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions Implement-Laptop-Allocation/implementLaptop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from dataclasses import dataclass
from enum import Enum
from typing import List, Dict


# Define possible operating systems
class OperatingSystem(Enum):
MACOS = "macOS"
ARCH = "Arch Linux"
UBUNTU = "Ubuntu"


# Define Person and Laptop
@dataclass
class Person:
name: str
age: int
preferred_operating_system: List[OperatingSystem]


@dataclass
class Laptop:
id: int
manufacturer: str
model: str
operating_system: OperatingSystem


# Function to calculate sadness
def sadness_for_person(person: Person, laptop: Laptop) -> int:
"""How sad a person is with this laptop."""
if laptop.operating_system in person.preferred_operating_system:
return person.preferred_operating_system.index(laptop.operating_system)
else:
return 100 # Very sad if OS not in their list


# Simple laptop allocation
def allocate_laptops(people: List[Person], laptops: List[Laptop]) -> Dict[str, Laptop]:
"""
Give each person one laptop.
Try to reduce sadness.
"""
allocated = {}
available_laptops = laptops.copy()

for person in people:
best_laptop = None
best_sadness = 999

# Try to find the best laptop for this person
for laptop in available_laptops:
s = sadness_for_person(person, laptop)
if s < best_sadness:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How long will this loop within a loop run if you have a lot of people and laptops as input? Can you think of any way to complete the loop early if you find a perfect match early on?

best_sadness = s
best_laptop = laptop

# Give them the best one we found
allocated[person.name] = best_laptop
available_laptops.remove(best_laptop)

return allocated


# Testing data
def main():
laptops = [
Laptop(1, "Dell", "XPS 13", OperatingSystem.ARCH),
Laptop(2, "Dell", "XPS 15", OperatingSystem.UBUNTU),
Laptop(3, "Apple", "MacBook Air", OperatingSystem.MACOS),
Laptop(4, "Dell", "Inspiron", OperatingSystem.UBUNTU),
]

people = [
Person("Imran", 22, [OperatingSystem.UBUNTU, OperatingSystem.ARCH, OperatingSystem.MACOS]),
Person("Eliza", 34, [OperatingSystem.ARCH, OperatingSystem.UBUNTU, OperatingSystem.MACOS]),
Person("Sam", 29, [OperatingSystem.MACOS, OperatingSystem.UBUNTU]),
Person("Tariq", 25, [OperatingSystem.ARCH]),
]

allocations = allocate_laptops(people, laptops)

print("=== Laptop Allocations ===")
total_sadness = 0
for name, laptop in allocations.items():
person = next(p for p in people if p.name == name)
sad = sadness_for_person(person, laptop)
total_sadness += sad
print(f"{name} gets {laptop.model} ({laptop.operating_system.value}) - sadness {sad}")

print(f"\nTotal sadness: {total_sadness}")


if __name__ == "__main__":
main()
89 changes: 89 additions & 0 deletions Prep Exercises/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
from enum import Enum
import sys

# Define the possible operating systems as an enum
class OperatingSystem(Enum):
MACOS = "MacOS"
ARCH = "Arch"
UBUNTU = "Ubuntu"

# List of laptops available in the library
laptops = [
{"id": 1, "manufacturer": "Dell", "model": "XPS", "os": OperatingSystem.ARCH},
{"id": 2, "manufacturer": "Dell", "model": "XPS", "os": OperatingSystem.UBUNTU},
{"id": 3, "manufacturer": "Dell", "model": "XPS", "os": OperatingSystem.UBUNTU},
{"id": 4, "manufacturer": "Apple", "model": "MacBook", "os": OperatingSystem.MACOS},
{"id": 5, "manufacturer": "Dell", "model": "Inspiron", "os": OperatingSystem.UBUNTU},
]

def get_user_preferences():
"""Get the user's name and preferred operating system"""
name = input("Enter your name: ").strip()
if not name:
print("Error: Name cannot be empty", file=sys.stderr)
sys.exit(1)

print("\nAvailable operating systems:")
print("• MacOS")
print("• Arch")
print("• Ubuntu")

os_choice = input("Enter your preferred operating system: ").strip().lower()

# Convert string to OperatingSystem enum
if os_choice == "macos":
return name, OperatingSystem.MACOS
elif os_choice == "arch":
return name, OperatingSystem.ARCH
elif os_choice == "ubuntu":
return name, OperatingSystem.UBUNTU
else:
print(f"Error: '{os_choice}' is not a valid operating system", file=sys.stderr)
print("Please choose from: macos, arch, ubuntu", file=sys.stderr)
sys.exit(1)

def count_laptops_by_os():
"""Count how many laptops we have for each operating system"""
counts = {}
for os in OperatingSystem:
counts[os] = 0

for laptop in laptops:
counts[laptop["os"]] += 1

return counts

def main():
print("=== Library Laptop Finder ===")

# Get user input
name, preferred_os = get_user_preferences()

# Count laptops for each OS
os_counts = count_laptops_by_os()

# Show results to user
user_laptop_count = os_counts[preferred_os]

print(f"\nHello {name}!")
print(f"We have {user_laptop_count} laptop(s) with {preferred_os.value}.")

# Check if other OS have more laptops
other_options = []
for os, count in os_counts.items():
if os != preferred_os and count > user_laptop_count:
other_options.append((os, count))

if other_options:
print("\nTip: These operating systems have more laptops available:")
for os, count in other_options:
print(f" • {os.value}: {count} laptops")

# Show complete availability
print(f"\nAll available laptops:")
for os in OperatingSystem:
count = os_counts[os]
print(f" • {os.value}: {count} laptop(s)")

if __name__ == "__main__":
main()
37 changes: 37 additions & 0 deletions Prep Exercises/inheritance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Parent:
def __init__(self, first_name: str, last_name: str):
self.first_name = first_name
self.last_name = last_name

def get_name(self) -> str:
return f"{self.first_name} {self.last_name}"


class Child(Parent):
def __init__(self, first_name: str, last_name: str):
super().__init__(first_name, last_name)
self.previous_last_names = []

def change_last_name(self, last_name) -> None:
self.previous_last_names.append(self.last_name)
self.last_name = last_name

def get_full_name(self) -> str:
suffix = ""
if len(self.previous_last_names) > 0:
suffix = f" (née {self.previous_last_names[0]})"
return f"{self.first_name} {self.last_name}{suffix}"

person1 = Child("Elizaveta", "Alekseeva")
print(person1.get_name())
print(person1.get_full_name())
person1.change_last_name("Tyurina")
print(person1.get_name())
print(person1.get_full_name())

person2 = Parent("Elizaveta", "Alekseeva")
print(person2.get_name())
# print(person2.get_full_name())
# person2.change_last_name("Tyurina")
print(person2.get_name())
# print(person2.get_full_name())
Loading