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
24 changes: 24 additions & 0 deletions sprint5/data_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from dataclasses import dataclass
from datetime import date

@dataclass(frozen=True)
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,today.day)<(self.date_of_birth.month,self.date_of_birth.day):
age-=1
return age>=18



imran = Person("Imran", date(2001, 9, 16), "Ubuntu")
print(imran)
print(imran.is_adult())

75 changes: 75 additions & 0 deletions sprint5/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
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

laptops = [
Laptop(1, "Dell", "XPS", 13, OperatingSystem.ARCH),
Laptop(2, "Dell", "XPS", 15, OperatingSystem.UBUNTU),
Laptop(3, "Dell", "XPS", 15, OperatingSystem.UBUNTU),
Laptop(4, "Apple", "macBook", 13, OperatingSystem.MACOS),
]

def get_name() -> str:
while True:
name = input("Name: ").strip()
if name:
return name
print("Name cannot be empty.")

def get_age() -> int:
while True:
age_input = input("Age: ").strip()
try:
age=int(age_input)
if age>0:
return age
else:
print("Age must be a positive number.")
except ValueError:
print("Age must be a number.")
def get_os() -> OperatingSystem:
os_values = [os.value for os in OperatingSystem]
while True:
os_input = input(f"Preferred OS ({', '.join(os_values)}): ").strip()
try:
return OperatingSystem(os_input)
except ValueError:
print(f"'{os_input}' is not a valid operating system. Please try again.")

name=get_name()
age=get_age()
preferred_os=get_os()

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

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]

possible_laptops = find_possible_laptops(laptops, person)
print(f"There are {len(possible_laptops)} laptops matching your preferred OS ({person.preferred_operating_system.value}).")

other_counts = {os: sum(1 for l in laptops if l.operating_system == os) for os in OperatingSystem}
most_available_os = max(other_counts, key=other_counts.get)

if most_available_os != person.preferred_operating_system and other_counts[most_available_os] > len(possible_laptops):
print(f"If you are willing to accept {most_available_os.value}, there are more laptops available ({other_counts[most_available_os]}).")
33 changes: 33 additions & 0 deletions sprint5/exercise1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def open_account(balances:dict , name:str, amount:int):
balances[name] = amount

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

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

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

open_account(balances,"Tobi", int(9.13*100))
open_account(balances,"Olya", int(7.13*100))

total_pence = sum_balances(balances)
total_string = format_pence_as_string(total_pence)

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



22 changes: 22 additions & 0 deletions sprint5/exercise2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
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)


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

print(is_adult(imran))

def print_address(person: Person) -> str:
return person.country
21 changes: 21 additions & 0 deletions sprint5/generics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from dataclasses import dataclass
from typing import List

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

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

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

def print_family_tree(person: Person, level:int=0) -> None:
indent="-->" * level
print(f"{indent}{person.name} ({person.age})")
for child in person.children:
print_family_tree(child,level+1)

print_family_tree(imran)
37 changes: 37 additions & 0 deletions sprint5/inheritance.py

Choose a reason for hiding this comment

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

Can you explain why the errors in this file occur?

Copy link
Author

Choose a reason for hiding this comment

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

I got errors because the Parent class only has the get_name method. It cannot use the methods in the Child class. But when we create a Child object, it has all Parent methods and its own methods, so no errors happen. I commented out the lines that would give errors.

Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
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()) # it works because get_name inherited from Parent
print(person1.get_full_name()) # works because Child has get_full_name method
person1.change_last_name("Tyurina")
print(person1.get_name())
print(person1.get_full_name())

person2 = Parent("Elizaveta", "Alekseeva")
print(person2.get_name()) # it works because get_name is Parent method
# print(person2.get_full_name()) it doesn't work because Parent doesn't have this method
# person2.change_last_name("Tyurina") it doesn't work because Parent doesn't have this method
print(person2.get_name())
# print(person2.get_full_name())
19 changes: 19 additions & 0 deletions sprint5/methods.py

Choose a reason for hiding this comment

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

Can you explain the difference between methods and functions, and any benefits/disadvantages?

Copy link
Author

Choose a reason for hiding this comment

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

  • Functions are independent and can be used anywhere.
  • Methods are defined inside a class and usually work with the object’s data.
  • Functions can be reused, but to use object data, you need to pass it as a parameter.
  • Methods can access and change object data and help keep the code organized, but you need to create an object to use them.

Choose a reason for hiding this comment

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

Good answers!

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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(self) -> bool:
today=date.today()
age=today.year -self.date_of_birth.year

if(today.month,today.day)<(self.date_of_birth.month,self.date_of_birth.day):
age-=1
return age>=18

imran = Person("Imran", date(2001,9,16), "Ubuntu")
print(imran.is_adult())
42 changes: 42 additions & 0 deletions sprint5/type-guided_refactorings.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_system: 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 = []
for laptop in laptops:
if laptop.operating_system == person.preferred_operating_system:
possible_laptops.append(laptop)
return possible_laptops


people = [
Person(name="Imran", age=22, preferred_operating_system=["Ubuntu","Arch Linux"]),
Person(name="Eliza", age=34, preferred_operating_system=["Ubuntu","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}")