Skip to content

Commit 962c2b7

Browse files
committed
Complete all Perp exercises
1 parent a49c91e commit 962c2b7

10 files changed

Lines changed: 329 additions & 0 deletions

Perp-exercises/Generics6.1.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from dataclasses import dataclass
2+
3+
4+
@dataclass(frozen=True)
5+
class Person:
6+
name: str
7+
age: int
8+
children: list["Person"]
9+
10+
11+
fatma = Person(name="Fatma", age=22, children=[])
12+
aisha = Person(name="Aisha", age=17, children=[])
13+
14+
imran = Person(name="Imran", age=44, children=[fatma, aisha])
15+
16+
17+
def print_family_tree(person: Person) -> None:
18+
print(person.name)
19+
for child in person.children:
20+
print(f"- {child.name} ({child.age})")
21+
22+
23+
print_family_tree(imran)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
8+
imran = Person("Imran", 22, "Ubuntu")
9+
print(imran.name)
10+
# print(imran.address)
11+
12+
eliza = Person("Eliza", 34, "Arch Linux")
13+
print(eliza.name)
14+
# print(eliza.address)
15+
16+
17+
def is_adult(person: Person) -> bool:
18+
return person.age >= 18
19+
20+
21+
print(is_adult(imran))
22+
23+
24+
def is_student(person: Person) -> bool:
25+
return person.student

Perp-exercises/dataclase-5.1.py

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

Perp-exercises/enum8.1.py

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
from enum import Enum
2+
from typing import List
3+
from dataclasses import dataclass
4+
5+
6+
class OperatingSystem(Enum):
7+
MACOS = "macOS"
8+
ARCH = "Arch Linux"
9+
UBUNTU = "Ubuntu"
10+
11+
12+
@dataclass(frozen=True)
13+
class Laptop:
14+
id: int
15+
manufacturer: str
16+
model: str
17+
screen_size_in_inches: int
18+
operating_system: OperatingSystem
19+
20+
21+
@dataclass(frozen=True)
22+
class Person:
23+
name: str
24+
age: int
25+
preferred_operating_system: OperatingSystem
26+
27+
28+
laptops = [
29+
Laptop(
30+
id=1,
31+
manufacturer="Dell",
32+
model="XPS",
33+
screen_size_in_inches=13,
34+
operating_system=OperatingSystem.ARCH,
35+
),
36+
Laptop(
37+
id=2,
38+
manufacturer="Dell",
39+
model="XPS",
40+
screen_size_in_inches=15,
41+
operating_system=OperatingSystem.UBUNTU,
42+
),
43+
Laptop(
44+
id=3,
45+
manufacturer="Dell",
46+
model="XPS",
47+
screen_size_in_inches=15,
48+
operating_system=OperatingSystem.UBUNTU,
49+
),
50+
Laptop(
51+
id=4,
52+
manufacturer="Apple",
53+
model="macBook",
54+
screen_size_in_inches=13,
55+
operating_system=OperatingSystem.MACOS,
56+
),
57+
]
58+
59+
60+
def group_laptops_by_operating_system(
61+
laptops: List[Laptop],
62+
) -> dict[OperatingSystem, List[Laptop]]:
63+
available_laptops: dict[OperatingSystem, List[Laptop]] = {
64+
OperatingSystem.UBUNTU: [],
65+
OperatingSystem.ARCH: [],
66+
OperatingSystem.MACOS: [],
67+
}
68+
for laptop in laptops:
69+
available_laptops[laptop.operating_system].append(laptop)
70+
71+
return available_laptops
72+
73+
74+
def how_many_match(
75+
person: Person, available_laptops: dict[OperatingSystem, List[Laptop]]
76+
) -> int:
77+
return len(available_laptops[person.preferred_operating_system])
78+
79+
80+
def most_available_operating_system(
81+
available_laptops: dict[OperatingSystem, List[Laptop]],
82+
) -> OperatingSystem:
83+
if not available_laptops:
84+
raise ValueError("No operating systems available")
85+
max_len: int = -1
86+
most_available: OperatingSystem
87+
for key, val in available_laptops.items():
88+
if len(val) > max_len:
89+
max_len = len(val)
90+
most_available = key
91+
92+
return most_available
93+
94+
95+
def main() -> None:
96+
name: str = input("Name: ")
97+
age: int = int(input("Age: "))
98+
99+
print("""choose an operating system:
100+
1.Ubuntu
101+
2,Arch Linux
102+
3.macOs""")
103+
choice: int = int(input("Enter Your choice: "))
104+
os_map: dict[int, OperatingSystem] = {
105+
1: OperatingSystem.UBUNTU,
106+
2: OperatingSystem.ARCH,
107+
3: OperatingSystem.MACOS,
108+
}
109+
110+
preferred_operating_system: OperatingSystem = os_map[choice]
111+
112+
person1: Person = Person(name, age, preferred_operating_system)
113+
114+
laptops_by_operating_system = group_laptops_by_operating_system(laptops)
115+
matching_laptop_count: int = how_many_match(person1, laptops_by_operating_system)
116+
print("We have", matching_laptop_count, "matches")
117+
most_available_os: OperatingSystem = most_available_operating_system(
118+
laptops_by_operating_system
119+
)
120+
if person1.preferred_operating_system != most_available_os:
121+
print("Are you willing to accept ", most_available_os.value, "instead")
122+
123+
124+
if __name__ == "__main__":
125+
main()

Perp-exercises/exercises1-1.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Predict what double("22") will do. Then run the code and check.
2+
# Did it do what you expected? Why did it return the value it did?
3+
4+
# answer
5+
# I predict that will return undefined or raise an error. However, it returned "2222"
6+
# because double function repeats the string twice

Perp-exercises/exercises1-2.py

Whitespace-only changes.

Perp-exercises/inheritance9.1.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Parent: # Implement a class called Parent
2+
def __init__(
3+
self, first_name: str, last_name: str
4+
): # Constructor that initializes the object's attributes.
5+
self.first_name = first_name # Create the 'first_name' attribute and assign the constructor argument to it
6+
self.last_name = last_name
7+
8+
def get_name(self) -> str: # Return the person's first name.
9+
return f"{self.first_name} {self.last_name}"
10+
11+
12+
class Child(Parent): # Implement a class called Child that inherit the class Parent
13+
def __init__(
14+
self, first_name: str, last_name: str
15+
): # Constructor for derived class
16+
super().__init__(
17+
first_name, last_name
18+
) # call the parent class to initialize inherited attributes.
19+
self.previous_last_names = [] # Create a list to store Previous last names
20+
21+
def change_last_name(
22+
self, last_name: str
23+
) -> None: # implement a function that take one parameter (the new name)
24+
self.previous_last_names.append(
25+
self.last_name
26+
) # and store the last name before setting a new value
27+
self.last_name = last_name
28+
29+
def get_full_name(
30+
self,
31+
) -> (
32+
str
33+
): # declare a var and return full name with "nee "and fist name that assign when the object where declare
34+
suffix = ""
35+
if len(self.previous_last_names) > 0:
36+
suffix = f" (née {self.previous_last_names[0]})"
37+
return f"{self.first_name} {self.last_name}{suffix}"
38+
39+
40+
person1 = Child(
41+
"Elizaveta", "Alekseeva"
42+
) # declare an object of Child class and give two arguments as firstname and last name
43+
print(person1.get_name()) # print full name (Elizaveta Alekseeva)
44+
print(
45+
person1.get_full_name()
46+
) # print full name (Elizaveta Alekseeva) we did not change the last name yet
47+
person1.change_last_name(
48+
"Tyurina"
49+
) # store the last name in pervious_last_name list then set a new value for last name "Tyurina"
50+
print(person1.get_name()) # #print full name (Elizaveta Tyurina)
51+
print(person1.get_full_name()) # print Elizaveta Tyurina (née Alekseeva)
52+
person2 = Parent(
53+
"Elizaveta", "Alekseeva"
54+
) # declare an object of Parent class and give two arguments as firstname and last name
55+
print(person2.get_name()) # print full name (Elizaveta Alekseeva)
56+
# print(person2.get_full_name()) # Error: Parent does not define get_full_name().
57+
# person2.change_last_name("Tyurina") ## Error: Parent does not define change_last_name().
58+
print(person2.get_name()) # print full name (Elizaveta Alekseeva)
59+
# print(person2.get_full_name()) # Error: Parent does not define get_full_name().

Perp-exercises/method4.2.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from datetime import date
2+
3+
4+
class Person:
5+
def __init__(self, name: str, date_of_birth: date, preferred_operating_system: str):
6+
self.name = name
7+
self.date_of_birth = date_of_birth
8+
self.preferred_operating_system = preferred_operating_system
9+
10+
def age(self) -> int:
11+
current: date = date.today()
12+
age: int = current.year - self.date_of_birth.year
13+
if (current.month, current.day) < (
14+
self.date_of_birth.month,
15+
self.date_of_birth.day,
16+
):
17+
age -= 1
18+
return age
19+
20+
def is_adult(self) -> bool:
21+
return self.age() >= 18
22+
23+
24+
imran = Person("Imran", date(2022, 10, 16), "Ubuntu")
25+
print(imran.is_adult())
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Think of the advantages of using methods instead of free functions. Write them down in your notebook.
2+
# Polymorphism – Derived classes can override methods to provide different behavior.
3+
# Encapsulation – Methods operate on the object's data (self), keeping data and behavior together.
4+
# Inheritance – Methods are inherited by derived classes, reducing code duplication.
5+
# Direct access to object state – Methods can access the object's attributes and other methods through self.

Perp-exercises/mypy-exercise2.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def open_account(balances: dict[str, int], name: str, amount: int) -> None:
2+
balances[name] = amount
3+
4+
5+
def sum_balances(accounts: dict[str, int]) -> int:
6+
total: int = 0
7+
for name, pence in accounts.items():
8+
print(f"{name} had balance {pence}")
9+
total += pence
10+
return total
11+
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+
21+
balances: dict[str, int] = {
22+
"Sima": 700,
23+
"Linn": 545,
24+
"Georg": 831,
25+
}
26+
27+
28+
open_account(balances, "Tobi", 913)
29+
open_account(balances, "Olya", 713)
30+
31+
total_pence = sum_balances(balances)
32+
total_string = format_pence_as_string(total_pence)
33+
34+
print(f"The bank accounts total {total_string}")

0 commit comments

Comments
 (0)