Skip to content
24 changes: 24 additions & 0 deletions dataclasses_ex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from datetime import date
from dataclasses import dataclass

@dataclass(frozen=True)
class Person:
name: str
preferred_operating_system: str
birth_date: date

def is_adult(self) -> bool:
today = date.today()
age = today.year - self.birth_date.year

if (today.month, today.day) < (self.birth_date.month, self.birth_date.day):
age -=1

return age >= 18

imran = Person("Imran", "Ubuntu", date(2000, 9, 12))

print(imran.is_adult())



105 changes: 105 additions & 0 deletions enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
from dataclasses import dataclass
from enum import Enum
from typing import List, Dict
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 count_laptops(laptops: List[Laptop]) -> Dict[OperatingSystem, int]:
number_eachOS_laptops: Dict[OperatingSystem, int] = {
OperatingSystem.MACOS: 0,
OperatingSystem.ARCH: 0,
OperatingSystem.UBUNTU: 0}
for laptop in laptops:
number_eachOS_laptops[laptop.operating_system] +=1
return number_eachOS_laptops


def count_possible_laptops(laptops: List[Laptop], person: Person) -> int:
possible_laptops: List[Laptop] =[]
for laptop in laptops:
if laptop.operating_system == person.preferred_operating_system:
possible_laptops.append(laptop)
number_possible_laptops = len(possible_laptops)
return number_possible_laptops

def chose_alternative_laptops(laptops: List[Laptop], person: Person) -> Dict[OperatingSystem, int]:
number_possible_laptops = count_possible_laptops(laptops, person)
number_eachOS_laptops = count_laptops(laptops)
preferred_os = person.preferred_operating_system
alternative_laptops: Dict[OperatingSystem, int] = {}
for eachOS, count in number_eachOS_laptops.items():
if eachOS == preferred_os:
continue
if count > number_possible_laptops:
alternative_laptops[eachOS] = count
if len(alternative_laptops) != 0:
print(f"There is an operating system that has more laptops available.If you’re willing to accept them, there is a list: {alternative_laptops}.")
return alternative_laptops
else:
print("There is not an operating system that has more laptops available.")
return alternative_laptops

while True:
user_name = input("Type your name: ").strip()
if len(user_name) < 3:
print(f"Error, {user_name} is not valid. Try again, length should be more than 3 characters.")
continue
break

while True:
user_age = input("Type your age: ").strip()
try:
user_age_int = int(user_age)
if user_age_int < 18:
raise ValueError
break
except ValueError:
print("Invalid age, try again! Borrowing allowed from 18 years old.")

available_os = [os.value for os in OperatingSystem]
print("Available OSs are: ", ",".join(available_os))
user_operating_system = input("Type operating system: ").strip()
if user_operating_system not in available_os:
print(f"Error, {user_operating_system} is not in available list\n"
f"Available OSs are: {','.join(available_os)}", file=sys.stderr)
sys.exit(1)

preferred_operating_system = OperatingSystem(user_operating_system)

user = Person(name=user_name, age=user_age_int, preferred_operating_system=preferred_operating_system)


laptops = [
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="Dell", model="XPS", screen_size_in_inches=15, operating_system=OperatingSystem.UBUNTU),
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system=OperatingSystem.MACOS),
]


possible_laptops = count_possible_laptops(laptops, user)
print(f"Possible laptops for {user_name}: {possible_laptops}")
alternative_laptops = chose_alternative_laptops(laptops, user)
20 changes: 20 additions & 0 deletions familytree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from dataclasses import dataclass
from typing import List

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

fatma = Person(name="Fatma", children=[], age=17)
aisha = Person(name="Aisha", children=[], age=25)

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

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

print_family_tree(imran)
39 changes: 39 additions & 0 deletions inherit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from typing import List

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: List [str]= []

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

def get_full_name(self) -> str:
suffix: str = ""
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 method dose not belong to Parent class
# person2.change_last_name("Tyurina") // this method dose not belong to Parent class
print(person2.get_name())
# print(person2.get_full_name()) // this method dose not belong to Parent class
42 changes: 42 additions & 0 deletions type_guide_refact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from dataclasses import dataclass
from typing import List

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


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


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


people = [
Person(name="Imran", age=22, preferred_operating_systems=["Ubuntu"]),
Person(name="Eliza", age=34, preferred_operating_systems=["Arch Linux"]),
]

laptops = [
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system="Arch Linux"),
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="Ubuntu"),
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="ubuntu"),
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system="macOS"),
]

for person in people:
possible_laptops = find_possible_laptops(laptops, person)
print(f"Possible laptops for {person.name}: {possible_laptops}")
33 changes: 33 additions & 0 deletions typesExer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import Union, Dict


def open_account(balances: Dict[str, int], name: str, amount: Union[str, float]):
balances[name] = int(float(amount) *100)

def sum_balances(accounts: Dict[str, int]):
total = 0
for name, pence in accounts.items():
print(f"{name} had balance {pence}")
total += pence
return total

def format_pence_as_pound(total_pence: int) -> str:
if total_pence < 100:
return f"{total_pence}p"
pounds = total_pence // 100
pence = total_pence % 100
return f"£{pounds}.{pence:02d}"

balances = {
"Sima": 700,
"Linn": 545,
"Georg": 831,
}

open_account(balances, "Tobi", 9.13)
open_account(balances, "Olya", 7.13)

total_pence = sum_balances(balances)
total_pound = format_pence_as_pound(total_pence)

print(f"The bank accounts total {total_pound}")