Skip to content

Commit 95decf8

Browse files
committed
feat: implement prep-exercises for sprint 5
1 parent 4350f48 commit 95decf8

9 files changed

Lines changed: 291 additions & 0 deletions

File tree

prep-exercises/check_with_mypy.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import Dict
2+
3+
def open_account(balances: Dict[str, int], name: str, amount: int) -> None:
4+
balances[name] = amount
5+
6+
def sum_balances(accounts: Dict[str, int]) -> int:
7+
total: int = 0
8+
for name, pence in accounts.items():
9+
print(f"{name} had balance {pence}")
10+
total += pence
11+
return total
12+
13+
def format_pence_as_string(total_pence: int) -> str:
14+
if total_pence < 100:
15+
return f"{total_pence}p"
16+
pounds = int(total_pence / 100)
17+
pence = total_pence % 100
18+
return f"£{pounds}.{pence:02d}"
19+
20+
balances: Dict[str, int] = {
21+
"Sima": 700,
22+
"Linn": 545,
23+
"Georg": 831,
24+
}
25+
26+
open_account(balances, "Tobi", 913)
27+
open_account(balances, "Olya", 713)
28+
29+
total_pence = sum_balances(balances)
30+
total_string = format_pence_as_string(total_pence)
31+
32+
print(f"The bank accounts total {total_string}")

prep-exercises/double.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def double(value):
2+
return value * 2
3+
4+
# Prediction - Since a string was passed as parameter, it will concatenate twice rather than multiply the number.
5+
6+
print(double("22"))
7+
8+
def double_number(value):
9+
return value * 3
10+
# The bug is multiplying by 3 rather than 2 as the function name implies.
11+
# To fix this, simply return value * 2
12+
13+
print(double_number(10))

prep-exercises/enums.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from dataclasses import dataclass
2+
from enum import Enum
3+
from typing import List
4+
5+
class OperatingSystem(Enum):
6+
MACOS = "macOS"
7+
ARCH = "Arch Linux"
8+
UBUNTU = "Ubuntu"
9+
10+
@dataclass(frozen=True)
11+
class Person:
12+
name: str
13+
age: int
14+
preferred_operating_system: OperatingSystem
15+
16+
@dataclass(frozen=True)
17+
class Laptop:
18+
id: int
19+
manufacturer: str
20+
model: str
21+
screen_size_in_inches: float
22+
operating_system: OperatingSystem
23+
24+
laptops = [
25+
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system=OperatingSystem.ARCH),
26+
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system=OperatingSystem.UBUNTU),
27+
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system=OperatingSystem.UBUNTU),
28+
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system=OperatingSystem.MACOS),
29+
]
30+
31+
def count_laptops(laptops: List[Laptop], operating_system: OperatingSystem) -> int:
32+
count = 0
33+
for laptop in laptops:
34+
if laptop.operating_system == operating_system:
35+
count += 1
36+
return count
37+
38+
def most_available_os(laptops: List[Laptop]) -> OperatingSystem:
39+
best_os = OperatingSystem.UBUNTU
40+
best_count = count_laptops(laptops, best_os)
41+
42+
for os in OperatingSystem:
43+
current_count = count_laptops(laptops, os)
44+
if current_count > best_count:
45+
best_count = current_count
46+
best_os = os
47+
48+
return best_os
49+
50+
name = input("Enter your name: ")
51+
age = int(input("Enter your age: "))
52+
os_input = input("Enter preferred OS (macOS, Arch Linux, Ubuntu): ")
53+
54+
try:
55+
preferred_os = OperatingSystem(os_input)
56+
except ValueError:
57+
print("Invalid operating system.")
58+
exit()
59+
60+
person = Person(name, age, preferred_os)
61+
62+
available = count_laptops(laptops, person.preferred_operating_system)
63+
64+
print(
65+
f"\nThere are {available} {person.preferred_operating_system.value} laptop(s) available."
66+
)
67+
68+
best_os = most_available_os(laptops)
69+
70+
if best_os != person.preferred_operating_system:
71+
print(
72+
f"If you're willing to accept {best_os.value}, you're more likely to get a laptop."
73+
)

prep-exercises/inheritance.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Parent:
2+
# Initialise the class
3+
def __init__(self, first_name: str, last_name: str):
4+
self.first_name = first_name
5+
self.last_name = last_name
6+
7+
# Gets first_name and last_name from Parent class
8+
def get_name(self) -> str:
9+
return f"{self.first_name} {self.last_name}"
10+
11+
12+
class Child(Parent):
13+
# setup Child class from the superclass Parent
14+
# has a new field for previous last names
15+
def __init__(self, first_name: str, last_name: str):
16+
super().__init__(first_name, last_name)
17+
self.previous_last_names = []
18+
19+
# changes the previous lastname to a new provided lastname and adds the prev lastname to a list
20+
def change_last_name(self, last_name) -> None:
21+
self.previous_last_names.append(self.last_name)
22+
self.last_name = last_name
23+
24+
# creates a suffix and appends to fullname if the prev lastname List is not empty
25+
def get_full_name(self) -> str:
26+
suffix = ""
27+
if len(self.previous_last_names) > 0:
28+
suffix = f" (née {self.previous_last_names[0]})"
29+
return f"{self.first_name} {self.last_name}{suffix}"
30+
31+
# creates an instance of Child class which inherits from Parent class
32+
person1 = Child("Elizaveta", "Alekseeva")
33+
print(person1.get_name()) # Elizaveta Alekseeva
34+
print(person1.get_full_name()) # Elizaveta Alekseeva
35+
# Changes the lastname to "Tyurina" and append Alekseeva to the previous_last_name List
36+
person1.change_last_name("Tyurina")
37+
print(person1.get_name()) # Elizaveta Tyurina
38+
print(person1.get_full_name()) # Elizaveta Tyurina (née Alekseeva)
39+
40+
# creates an instance of Parent class
41+
person2 = Parent("Elizaveta", "Alekseeva")
42+
print(person2.get_name()) # Elizaveta Alekseeva
43+
print(person2.get_full_name()) # Error: Parent class does not have the get_full_name() method/attribute and program crashes
44+
person2.change_last_name("Tyurina") # Error: Parent class does not have the change_last_name() method, program crash
45+
print(person2.get_name()) # Elizaveta Alekseeva
46+
print(person2.get_full_name()) # Error: Parent class does not have the get_full_name() method/attribute, program crash

prep-exercises/person_class.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Person:
2+
def __init__(self, name: str, age: int, preferred_operating_system: str):
3+
self.name = name
4+
self.age = age
5+
self.preferred_operating_system = preferred_operating_system
6+
7+
imran = Person("Imran", 22, "Ubuntu")
8+
print(imran.name)
9+
# print(imran.address) - Person class has no address attribute, hence the error message in mypy on lines 9 and 13
10+
11+
eliza = Person("Eliza", 34, "Arch Linux")
12+
print(eliza.name)
13+
# print(eliza.address) - same as line 9
14+
15+
def is_adult(person: Person) -> bool:
16+
return person.age >= 18
17+
18+
print(is_adult(imran))
19+
20+
# This function will generate an attribute error when mypy runs it, because gender is not an attribute of the class, Person.
21+
def check_gender(person: Person) -> str:
22+
return person.gender

prep-exercises/person_dataclass.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from datetime import date
2+
from dataclasses import dataclass
3+
4+
@dataclass(frozen=True)
5+
class Person:
6+
name: str
7+
date_of_birth: date
8+
preferred_operating_system: str
9+
10+
def is_adult(self) -> bool:
11+
today = date.today()
12+
13+
age = today.year - self.date_of_birth.year
14+
15+
if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
16+
age -= 1
17+
18+
return age >= 18
19+
20+
imran = Person("Imran", date(2000, 10, 11), "Ubuntu")
21+
print(imran)
22+
print(imran.is_adult())

prep-exercises/person_generics.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from dataclasses import dataclass
2+
from typing import List
3+
# from datetime import date
4+
5+
@dataclass(frozen=True)
6+
class Person:
7+
name: str
8+
age: int
9+
children: List["Person"]
10+
11+
fatma = Person(name="Fatma", age=10, children=[])
12+
aisha = Person(name="Aisha", age=7, children=[])
13+
14+
imran = Person(name="Imran", age=38, children=[fatma, aisha])
15+
16+
def print_family_tree(person: Person) -> None:
17+
print(person.name)
18+
for child in person.children:
19+
print(f"- {child.name} ({child.age})")
20+
21+
print_family_tree(imran)

prep-exercises/person_method.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import datetime as dt
2+
3+
class Person:
4+
def __init__(self, name: str, dob: dt.date, preferred_operating_system: str):
5+
self.name = name
6+
self.dob = dob
7+
self.preferred_operating_system = preferred_operating_system
8+
9+
def is_adult(self) -> bool:
10+
today = dt.date.today()
11+
12+
age = today.year - self.dob.year
13+
14+
if (today.month, today.day) < (self.dob.month, self.dob.day):
15+
age -= 1
16+
17+
return age >= 18
18+
19+
imran = Person("Imran", dt.date(1998, 11, 13), "Ubuntu")
20+
print(imran.is_adult())

prep-exercises/type_refactoring.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from dataclasses import dataclass
2+
from typing import List
3+
4+
@dataclass(frozen=True)
5+
class Person:
6+
name: str
7+
age: int
8+
preferred_operating_systems: List[str]
9+
10+
11+
@dataclass(frozen=True)
12+
class Laptop:
13+
id: int
14+
manufacturer: str
15+
model: str
16+
screen_size_in_inches: float
17+
operating_system: str
18+
19+
20+
def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]:
21+
possible_laptops = []
22+
for laptop in laptops:
23+
if laptop.operating_system == person.preferred_operating_systems[0]:
24+
possible_laptops.append(laptop)
25+
return possible_laptops
26+
27+
28+
people = [
29+
Person(name="Imran", age=22, preferred_operating_systems=["Ubuntu", "Arch Linux"]),
30+
Person(name="Eliza", age=34, preferred_operating_systems=["Arch Linux", "macOS"]),
31+
]
32+
33+
laptops = [
34+
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system="Arch Linux"),
35+
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="Ubuntu"),
36+
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="ubuntu"),
37+
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system="macOS"),
38+
]
39+
40+
for person in people:
41+
possible_laptops = find_possible_laptops(laptops, person)
42+
print(f"Possible laptops for {person.name}: {possible_laptops}")

0 commit comments

Comments
 (0)