Skip to content

Commit 01aed45

Browse files
committed
prep-exercises folder
1 parent 294b028 commit 01aed45

File tree

8 files changed

+442
-0
lines changed

8 files changed

+442
-0
lines changed

prep-exercices/Methods.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# EXERCISE 1: Think of the advantages of using methods instead of free functions. Write them down in your notebook
2+
# - Methods keep data and behavior together
3+
# - Methods make code easier to read
4+
# - Methods reduce mistakes
5+
# - Easier to extend and maintain
6+
# - Methods support inheritance
7+
# - Better organization
8+
# - Better organization
9+
# - Methods enable polymorphism
10+
11+
12+
13+
# EXERCISE 2: 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.
14+
# Update the is_adult method to act the same as before.
15+
16+
17+
from datetime import date
18+
from dataclasses import dataclass
19+
20+
@dataclass (frozen=True)
21+
class Person:
22+
name: str
23+
date_of_birth: date
24+
preferred_operating_system: str
25+
26+
def is_adult(self) -> bool:
27+
today = date.today()
28+
age = today.year - self.date_of_birth.year
29+
30+
# Adjust if birthday hasn't happened yet this year
31+
if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
32+
age -= 1
33+
return age >= 18
34+
35+
imran = Person("Jesus", date(1980, 1, 12), "Ubuntu")
36+
print(imran.is_adult())
37+
38+

prep-exercices/class-and-object.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#Read the error, and make sure you understand what it’s telling you.
2+
3+
4+
5+
class Person:
6+
def __init__(self, name: str, age: int, preferred_operating_system: str):
7+
self.name = name
8+
self.age = age
9+
self.preferred_operating_system = preferred_operating_system
10+
11+
12+
13+
imran = Person("Imran", 22, "Ubuntu")
14+
print(imran.name)
15+
16+
17+
eliza = Person("Eliza", 34, "Arch Linux")
18+
print(eliza.name)
19+
20+
def is_adult(person: Person) -> bool:
21+
return person.age >= 18
22+
23+
print(is_adult(imran))
24+
25+
26+
def address(person: Person) -> str:
27+
return person.address
28+
29+
30+
#EXERCISE 1:
31+
#Add the is_adult code to the file you saved earlier.
32+
#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.
33+
# 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.
34+
35+
# SOLUTION:
36+
# After run class-and-object.py, I get the following mypy errors:
37+
# class-and-object.py:12: error: "Person" has no attribute "address"
38+
# It indicates that the Person class does not have an attribute named address.
39+
40+
#EXERCISE 2:
41+
# Add the is_adult code to the file you saved earlier
42+
# 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.
43+
44+
# 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.
45+
# When running mypy, I get the following error:
46+
# Class-and-object.py:27: error: "Person" has no attribute "address" [attr-defined]
47+
# Found 1 error in 1 file (checked 1 source file)
48+
# This error indicates that the Person class does not have an attribute named address.

prep-exercices/data-classes.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
# Write a Person class using @datatype which uses a datetime.date for date of birth, rather than an int for age.
3+
# Re-add the is_adult method to it.
4+
5+
from datetime import date
6+
from dataclasses import dataclass
7+
8+
@dataclass (frozen=True)
9+
class Person:
10+
name: str
11+
date_of_birth: date
12+
preferred_operating_system: str
13+
14+
def is_adult(self) -> bool:
15+
today = date.today()
16+
age = today.year - self.date_of_birth.year
17+
18+
# Adjust if birthday hasn't happened yet this year
19+
if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
20+
age -= 1
21+
return age >= 18
22+
23+
jesus = Person("Jesus", date(1980, 1, 12), "Ubuntu")
24+
print(jesus.is_adult())
25+

prep-exercices/enumeration.py

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
2+
# EXERCISE 1:
3+
# Write a program which:
4+
5+
# Already has a list of Laptops that a library has to lend out.
6+
# 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.
7+
# Tells the user how many laptops the library has that have that operating system.
8+
# 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.
9+
# 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.
10+
11+
# SOLUTION:
12+
13+
import sys
14+
from dataclasses import dataclass
15+
from enum import Enum
16+
from typing import List
17+
18+
class OperatingSystem(Enum):
19+
MACOS = "macOS"
20+
ARCH = "Arch Linux"
21+
UBUNTU = "Ubuntu"
22+
23+
@dataclass(frozen=True)
24+
class Person:
25+
name: str
26+
age: int
27+
preferred_operating_system: OperatingSystem
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: OperatingSystem
36+
37+
# Predefined laptops
38+
laptops = [
39+
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system=OperatingSystem.ARCH),
40+
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system=OperatingSystem.UBUNTU),
41+
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system=OperatingSystem.UBUNTU),
42+
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system=OperatingSystem.MACOS),
43+
]
44+
45+
def count_laptops_by_os(laptops: List[Laptop]) -> dict:
46+
os_count = {os: 0 for os in OperatingSystem}
47+
for laptop in laptops:
48+
os_count[laptop.operating_system] += 1
49+
return os_count
50+
51+
def main():
52+
# --- Input name ---
53+
name = input("Enter your name: ").strip()
54+
if not name:
55+
print("Error: Name cannot be empty.", file=sys.stderr)
56+
sys.exit(1)
57+
58+
# --- Input age ---
59+
age_input = input("Enter your age: ").strip()
60+
try:
61+
age = int(age_input)
62+
if age <= 0:
63+
raise ValueError()
64+
except ValueError:
65+
print("Error: Age must be a positive integer.", file=sys.stderr)
66+
sys.exit(1)
67+
68+
# --- Input preferred OS ---
69+
print("Choose preferred operating system:")
70+
for os in OperatingSystem:
71+
print(f"- {os.value}")
72+
os_input = input("Enter OS: ").strip()
73+
74+
try:
75+
preferred_os = OperatingSystem(os_input)
76+
except ValueError:
77+
print("Error: Invalid operating system.", file=sys.stderr)
78+
sys.exit(1)
79+
80+
# --- Create Person ---
81+
new_person = Person(name=name, age=age, preferred_operating_system=preferred_os)
82+
83+
# --- Count laptops by OS ---
84+
os_count = count_laptops_by_os(laptops)
85+
86+
# --- Show count for user's preferred OS ---
87+
count_for_user_os = os_count.get(new_person.preferred_operating_system, 0)
88+
print(f"There are {count_for_user_os} laptops available with {new_person.preferred_operating_system.value}.")
89+
90+
# --- Find the OS with most laptops ---
91+
max_os = max(os_count, key=os_count.get)
92+
max_count = os_count[max_os]
93+
94+
# Suggest alternative if more laptops are available
95+
if max_os != new_person.preferred_operating_system and max_count > count_for_user_os:
96+
print(f"Tip: There are more laptops available with {max_os.value} ({max_count} laptops). "
97+
f"If you're willing to accept that OS, you're more likely to get a laptop.")
98+
99+
if __name__ == "__main__":
100+
main()

prep-exercices/generics.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
#EXERCISE 1: Fix the above code so that it works. You must not change the print on line 17
3+
# we do want to print the children’s ages. (Feel free to invent the ages of Imran’s children)
4+
5+
# SOLUTION:
6+
7+
from dataclasses import dataclass
8+
from typing import List
9+
10+
@dataclass(frozen=True)
11+
class Person:
12+
name: str
13+
age: int = 0
14+
children: List["Person"]
15+
16+
fatma = Person(name="Fatma", age=18, children=[])
17+
aisha = Person(name="Aisha", age=24, children=[])
18+
19+
imran = Person(name="Imran", age=45, children=[fatma aisha])
20+
21+
def print_family_tree(person: Person) -> None:
22+
print(person.name)
23+
for child in person.children:
24+
print(f"- {child.name} ({child.age})")
25+
26+
print_family_tree(imran)

prep-exercices/inheritance.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
#EXERCISE 1::
3+
4+
#Play computer with this code. Predict what you expect each line will do.
5+
#Then run the code and check your predictions. (If any lines cause errors, you may need to comment them out to check later lines).
6+
7+
#SOLUTION:
8+
9+
# The first four prints will work fine, as the Child class inherits from the Parent class and has access to its methods.
10+
# The last four prints will get error because the Parent class does not have the methods get_full_name and change_last_name defined.
11+
# Fix the code we can comment out the last four lines or we can add the methods to the Parent class.
12+
13+
class Parent:
14+
def __init__(self, first_name: str, last_name: str):
15+
self.first_name = first_name
16+
self.last_name = last_name
17+
18+
def get_name(self) -> str:
19+
return f"{self.first_name} {self.last_name}"
20+
21+
22+
class Child(Parent):
23+
def __init__(self, first_name: str, last_name: str):
24+
super().__init__(first_name, last_name)
25+
self.previous_last_names = []
26+
27+
def change_last_name(self, last_name) -> None:
28+
self.previous_last_names.append(self.last_name)
29+
self.last_name = last_name
30+
31+
def get_full_name(self) -> str:
32+
suffix = ""
33+
if len(self.previous_last_names) > 0:
34+
suffix = f" (née {self.previous_last_names[0]})"
35+
return f"{self.first_name} {self.last_name}{suffix}"
36+
37+
person1 = Child("Elizaveta", "Alekseeva")
38+
print(person1.get_name())
39+
print(person1.get_full_name())
40+
person1.change_last_name("Tyurina")
41+
print(person1.get_name())
42+
print(person1.get_full_name())
43+
44+
"""
45+
person2 = Parent("Elizaveta", "Alekseeva")
46+
print(person2.get_name())
47+
print(person2.get_full_name())
48+
person2.change_last_name("Tyurina")
49+
print(person2.get_name())
50+
print(person2.get_full_name())
51+
"""

prep-exercices/type-checking.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# his code contains bugs related to types. They are bugs mypy can catch.
2+
3+
# Read this code to understand what it’s trying to do.
4+
# Add type annotations to the method parameters and return types of this code.
5+
# Run the code through mypy, and fix all of the bugs that show up.
6+
# When you’re confident all of the type annotations are correct, and the bugs are fixed, run the code and check it works.
7+
8+
9+
10+
def open_account(balances, name, amount):
11+
balances[name] = amount
12+
13+
def sum_balances(accounts):
14+
total = 0
15+
for name, pence in accounts.items():
16+
print(f"{name} had balance {pence}")
17+
total += pence
18+
return total
19+
20+
def format_pence_as_string(total_pence):
21+
if total_pence < 100:
22+
return f"{total_pence}p"
23+
pounds = int(total_pence / 100)
24+
pence = total_pence % 100
25+
return f"£{pounds}.{pence:02d}"
26+
27+
balances = {
28+
"Sima": 700,
29+
"Linn": 545,
30+
"Georg": 831,
31+
}
32+
33+
# convert pounds to pence
34+
open_account(balances, "Tobi", int(9.13 * 100)) # 913 pence
35+
open_account(balances, "Olya", int(7.13 * 100)) # 713 pence
36+
37+
total_pence = sum_balances(balances)
38+
total_string = format_pence_as_string(total_pence)
39+
40+
print(f"The bank accounts total {total_string}")
41+
42+
43+
44+
45+
# When running mypy, I get the following errors:
46+
47+
# type-checking.py:24: error: Missing positional argument "amount" in call to "open_account" [call-arg]
48+
# type-checking.py:25: error: Missing positional argument "amount" in call to "open_account" [call-arg]
49+
# type-checking.py:28: error: Name "format_pence_as_str" is not defined [name-defined]
50+
# type-checking.py:34: error: Missing positional argument "amount" in call to "open_account" [call-arg]
51+
# type-checking.py:35: error: Missing positional argument "amount" in call to "open_account" [call-arg]
52+
# type-checking.py:38: error: Name "format_pence_as_str" is not defined [name-defined]
53+
54+
55+
# To fix this code, I need to add type annotations and correct the function calls as follows:
56+
57+
# wrong arguments to open_account, the function expects three arguments: balances, name, and amount.
58+
# one call passes a string "£7.13" instead of a number.
59+
# Wrong function name format_pence_as_str instead of format_pence_as_string.
60+
# To keep the program consistent (Everything in pence), convert pounds to pence when opening accounts.
61+
62+
# Here is the corrected code:
63+
64+
"""
65+
def open_account(balances, name, amount):
66+
balances[name] = amount
67+
68+
def sum_balances(accounts):
69+
total = 0
70+
for name, pence in accounts.items():
71+
print(f"{name} had balance {pence}")
72+
total += pence
73+
return total
74+
75+
def format_pence_as_string(total_pence):
76+
if total_pence < 100:
77+
return f"{total_pence}p"
78+
pounds = int(total_pence / 100)
79+
pence = total_pence % 100
80+
return f"£{pounds}.{pence:02d}"
81+
82+
balances = {
83+
"Sima": 700,
84+
"Linn": 545,
85+
"Georg": 831,
86+
}
87+
88+
# convert pounds to pence
89+
open_account(balances, "Tobi", int(9.13 * 100)) # 913 pence
90+
open_account(balances, "Olya", int(7.13 * 100)) # 713 pence
91+
92+
total_pence = sum_balances(balances)
93+
total_string = format_pence_as_string(total_pence)
94+
95+
print(f"The bank accounts total {total_string}")
96+
"""
97+

0 commit comments

Comments
 (0)