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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
node_modules
**/.venv

1 change: 1 addition & 0 deletions implement-cowsay/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cowsay
Empty file.
25 changes: 25 additions & 0 deletions prep-exercises/classes_and_objects_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

# class Person:
# def __init__(self, name: str, age: int, preferred_operating_system: str):
# self.name = name
# self.age = age
# self.preferred_operating_system = preferred_operating_system

# imran = Person("Imran", 22, "Ubuntu")
# print(imran.name)
# print(imran.address)

# eliza = Person("Eliza", 34, "Arch Linux")
# print(eliza.name)
# print(eliza.address)

# --- Exercise ---
# Save the above code to a file, and run it through mypy.

# Read the error, and make sure you understand what it’s telling you.

# --- Solution ---
# The error reads as follows: "Person" has no attribute "address"
# This error occurs because we are trying to access an attribute "address" on the Person class, which has not been defined in the class constructor.
# To fix this error, we can either remove the lines that attempt to access the "address" attribute, or we can add an "address" attribute to the Person class constructor.
# self.address = "Unknown"
35 changes: 35 additions & 0 deletions prep-exercises/classes_and_objects_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Person:
def __init__(self, name: str, age: int, preferred_operating_system: str):
self.name = name
self.age = age
self.preferred_operating_system = preferred_operating_system
self.address = "Unknown"

imran = Person("Imran", 22, "Ubuntu")
print(imran.name)
print(imran.address)

eliza = Person("Eliza", 34, "Arch Linux")
print(eliza.name)
print(eliza.address)

def is_adult(person: Person) -> bool:
return person.age >= 18

print(is_adult(imran))

# Function added that accesses a non-existent property
def is_married(person: Person) -> bool:
return person.married == "Y" or person.married == "y"

print(is_married(imran))

# --- Exercise ---
# Add the is_adult code to the file you saved earlier.

# Run it through mypy - notice that no errors are reported - mypy understands that Person has a property named age so is happy with the function.

# Write a new function in the file that accepts a Person as a parameter and tries to access a property that doesn’t exist. Run it through mypy and check that it does report an error.

# --- Solution ---
# The error I received was: "Person" has no attribute "married"
21 changes: 21 additions & 0 deletions prep-exercises/dataclasses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# --- Exercise ---
# Write a Person class using @datatype which uses a datetime.date for date of birth, rather than an int for age.

# Re-add the is_adult method to it.

# --- Solution ---
from datetime import date
from dataclasses import dataclass

@dataclass
class Person:
name: str
date_of_birth: date
preferred_operating_system: str

def is_adult(self) -> bool:
today = date.today()
age = today.year - self.date_of_birth.year
if today.month < self.date_of_birth.month or (today.month == self.date_of_birth.month and today.day < self.date_of_birth.day):
age -= 1
return age >= 18
117 changes: 117 additions & 0 deletions prep-exercises/enums.py

Choose a reason for hiding this comment

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

When i try to run this file at the command line I get an error, can you figure out why that happens and fix it?

Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# --- Exercise ---
# Write a program which:

# 1. Already has a list of Laptops that a library has to lend out.
# 2. Accepts user input to create a new Person - it should use the input function to read a person’s name, age, and preferred operating system.
# 3. Tells the user how many laptops the library has that have that operating system.
# 4. If there is an operating system that has more laptops available, tells the user that if they’re willing to accept that operating system they’re more likely to get a laptop.

# You should convert the age and preferred operating system input from the user into more constrained types as quickly as possible, and should output errors to stderr and terminate the program with a non-zero exit code if the user input bad values.

# --- Solution ---
from dataclasses import dataclass
from enum import Enum
from typing import List
import sys


class OperatingSystem(Enum):
MACOS = "macOS"
ARCH = "Arch Linux"
UBUNTU = "Ubuntu"


@dataclass(frozen=True)
class Person:
name: str
age: int
preferred_operating_system: OperatingSystem


@dataclass(frozen=True)
class Laptop:
id: int
manufacturer: str
model: str
screen_size_in_inches: float
operating_system: OperatingSystem


def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]:
return [
laptop
for laptop in laptops
if laptop.operating_system == person.preferred_operating_system
]


def read_person_from_input() -> Person:
try:
name = input("Enter name: ").strip()
if not name:
raise ValueError("Name cannot be empty")

age_input = input("Enter age: ").strip()
age = int(age_input)
if age < 0:
raise ValueError("Age must be non-negative")

os_input = input(
"Enter preferred operating system (macOS, Arch Linux, Ubuntu): "
).strip()

preferred_os = OperatingSystem(os_input)

return Person(
name=name,
age=age,
preferred_operating_system=preferred_os,
)

except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)


LAPTOPS: List[Laptop] = [
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system=OperatingSystem.ARCH),
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system=OperatingSystem.UBUNTU),
Laptop(id=3, manufacturer="Lenovo", model="T14 G6", screen_size_in_inches=14, operating_system=OperatingSystem.UBUNTU),
Laptop(id=4, manufacturer="Apple", model="MacBook Air", screen_size_in_inches=13, operating_system=OperatingSystem.MACOS),
Laptop(id=5, manufacturer="Lenovo", model="X1 Carbon", screen_size_in_inches=13, operating_system=OperatingSystem.ARCH),
Laptop(id=6, manufacturer="HP", model="Pavilion", screen_size_in_inches=16, operating_system=OperatingSystem.UBUNTU),
Laptop(id=7, manufacturer="ASUS", model="ExpertBook B1", screen_size_in_inches=14, operating_system=OperatingSystem.ARCH),
Laptop(id=8, manufacturer="Apple", model="MacBook Pro", screen_size_in_inches=14, operating_system=OperatingSystem.MACOS),
]


def main() -> None:
person = read_person_from_input()

matching_laptops = find_possible_laptops(LAPTOPS, person)
print(
f"\nNumber of laptops available with "
f"{person.preferred_operating_system.value}: "
f"{len(matching_laptops)}"
)

laptops_per_os: dict[OperatingSystem, int] = {}
for laptop in LAPTOPS:
laptops_per_os[laptop.operating_system] = (
laptops_per_os.get(laptop.operating_system, 0) + 1
)

most_available_os = max(
laptops_per_os.items(),
key=lambda item: item[1],
)[0]

if most_available_os != person.preferred_operating_system:
print(
f"If you're willing to accept {most_available_os.value}, "
"you're more likely to get a laptop."
)


if __name__ == "__main__":
main()
45 changes: 45 additions & 0 deletions prep-exercises/generics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# from dataclasses import dataclass
# from typing import List

# @dataclass(frozen=True)
# class Person:
# name: str
# children: List["Person"]

# fatma = Person(name="Fatma", children=[])
# aisha = Person(name="Aisha", children=[])

# imran = Person(name="Imran", children=[fatma, aisha])

# def print_family_tree(person: Person) -> None:
# print(person.name)
# for child in person.children:
# print(f"- {child.name} ({child.age})")

# print_family_tree(imran)

# --- Exercise ---
# Fix the above code so that it works. You must not change the print on line 17 - we do want to print the children’s ages. (Feel free to invent the ages of Imran’s children.)

# --- Solution ---
from dataclasses import dataclass
from typing import List

@dataclass(frozen=True)
class Person:
name: str
age:int
children: List['Person']

fatma = Person(name="Fatma",age=13, children=[])
aisha = Person(name="Aisha",age=6, children=[])

imran = Person(name="Imran",age=42, children=[fatma, aisha])


def print_family_tree(person: Person) -> None:
print(person.name)
for child in person.children:
print(f"- {child.name} ({child.age})")

Choose a reason for hiding this comment

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

Could you find a way to recursively print a full family tree - including grandchildren?


print_family_tree(imran)
81 changes: 81 additions & 0 deletions prep-exercises/inheritance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# --- Exercise ---
# Play computer with this code. Predict what you expect each line will do. Then run the code and check your predictions. (If any lines cause errors, you may need to comment them out to check later lines).

# 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())

# --- Solution ---

# This defines a class called "Parent" with an initializer that sets the first and last name, and a method to get the full name.
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}"

# This defines a class called "Child" that inherits from "Parent". It has an initializer that calls the parent's initializer and adds a list that can track previous last names. It also has methods to change the last name and get the full name with any previous last names included.
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()) # This line will cause an error because the Parent class does not have a get_full_name method.
person2.change_last_name("Tyurina") # This line will cause an error because the Parent class does not have a change_last_name method.
print(person2.get_name())
print(person2.get_full_name()) # This line will cause an error because the Parent class does not have a get_full_name method.
8 changes: 8 additions & 0 deletions prep-exercises/methods_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# --- Exercise ---
# Think of the advantages of using methods instead of free functions. Write them down in your notebook.

# --- Solution ---
# Methods are bundled with the data they operate on, making the code more organised.
# Methods can be reused across different parts of the program.
# Methods make code more readable and easier to understand.
# Changes to the method's implementation only need to be made in one place.
21 changes: 21 additions & 0 deletions prep-exercises/methods_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# --- Exercise ---
# Change the Person class to take a date of birth (using the standard library’s datetime.date class) and store it in a field instead of age.

# Update the is_adult method to act the same as before.

# --- Solution ---
from datetime import date

class Person:
def __init__(self, name: str, date_of_birth: date, preferred_operating_system: str):
self.name = name
self.date_of_birth = date_of_birth
self.preferred_operating_system = preferred_operating_system

def is_adult(person: Person) -> bool:
today = date.today()
age = today.year - person.date_of_birth.year
if today.month < person.date_of_birth.month or (today.month == person.date_of_birth.month and today.day < person.date_of_birth.day):
age -= 1
return age >= 18

Loading