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
29 changes: 29 additions & 0 deletions sprint-5-exercises/add_is_adult.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@


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 is_developer(person: Person) -> bool:
return person.is_developer

print(is_developer(imran))

# As expected, there is an error because the is_developer attribute is not present in the Person class.
16 changes: 16 additions & 0 deletions sprint-5-exercises/advantage_of_using_methods.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Encapsulation:
Data and methods are packaged together to form one cohesive unit.
This allows great control of access and modification of the data,
presenting an interface to the user, and hiding the implementation details.

The class/object can impose rules on access and modification. E.g. balance can't
be negative.

Implementation can also be changed without breaking the interface which
should be reliable and consistent over time.

Ease of use:
Makes it easier for users of the data, as they only need to reason about
the interface, not the implementation details. E.g. methods that operate on an object
can be easily with the dot notation and IDE autocomplete.

33 changes: 33 additions & 0 deletions sprint-5-exercises/bank_account_annotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import Dict

def open_account(balances: Dict[str, int], name : str, amount: int) -> None:
balances[name] = amount

def sum_balances(accounts: Dict[str, int]) -> int:
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) -> str:
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,
}

# the amount is int pence not float pounds
open_account(balances, "Tobi", 913)
open_account(balances, "Olya", 713)

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

print(f"The bank accounts total {total_string}")
25 changes: 25 additions & 0 deletions sprint-5-exercises/dataclass_person.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# convert person class to a dataclass
import datetime as dt
from dataclasses import dataclass

@dataclass
class Person:
name: str
birthdate: dt.date
preferred_operating_system: str

def is_adult(self) -> bool:
today = dt.date.today()
years = today.year - self.birthdate.year
# python does a lexicographical comparison of the elements in the tuples
# only checks the days if the months are equal

had_birthday_this_year = (today.month, today.day) >= (self.birthdate.month, self.birthdate.day)
age = years if had_birthday_this_year else years - 1
return age >= 18

# note: the above is necessary because with my old version, if the original birthday is on feb 29
# then it would try to create a new date of feb 29 on a non-leap year and crash

imran = Person("Imran", dt.date(2009,8,6), "Ubuntu")
print(imran.is_adult())
7 changes: 7 additions & 0 deletions sprint-5-exercises/fix_double.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def double(number):
# return number * 3
return number * 2. # the fix

print(double(10))

# bug: function is called double, but returns tripple of what is given as input.
20 changes: 20 additions & 0 deletions sprint-5-exercises/generics.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=12)
aisha = Person(name="Aisha", children=[], age=15)

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

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

print_family_tree(imran)
44 changes: 44 additions & 0 deletions sprint-5-exercises/inheritance_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

# parent class has two string fields, first_name, last_name
# a method that return a string which joins the two names with a space
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}"


# extends parent class
# add ability to change last name, store previous last names in a list
# a method that prints first and last name as well as the original last name of Child
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()) # inherit from Parent class, output = "Elizaveta Alekseeva"
print(person1.get_full_name()) # method of Child class, output = "Elizaveta Alekseeva" no previous surname
person1.change_last_name("Tyurina") # changes last name of person1, adds "Alekseeva" to previous names list
print(person1.get_name()) # last name has changed, output = "Elizaveta Tyurina"
print(person1.get_full_name()) # includes maiden name, output = "Elizaveta Tyurina (née Alekseeva)"

person2 = Parent("Elizaveta", "Alekseeva")
print(person2.get_name()) # output = "Elizaveta Alekseeva"
print(person2.get_full_name()) # AttrbuteError - the Parent class does not have get_full_name() method
person2.change_last_name("Tyurina") # same again
print(person2.get_name()) # no problems, same as line 40
print(person2.get_full_name()) # again, no get_full_name() method in this Parent class. Same as line 41
99 changes: 99 additions & 0 deletions sprint-5-exercises/laptop_enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
from dataclasses import dataclass
from enum import Enum
from typing import List
from collections import Counter

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 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=OperatingSystem.UBUNTU),
# Person(name="Eliza", age=34, preferred_operating_system=OperatingSystem.ARCH),
# ]

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),
]


# take input (name, age, preferred os), create Person object
# show them how many laptops with their chosen OS are available
# if there is a different os with more laptops, tell user they are more likely to get a laptop
# if they choose that os

# loops forever until alphabetic string provided
def person_name_input() -> str:
name = input("Enter your first name: ")
while True:
if (name.isalpha()):
return name
name = input("invalid first name, please enter only letters: ")

# loops forever until numeric input is provided
def person_age_input() -> int:
age = input("Enter your age: ")
while True:
if (age.isnumeric()):
return int(age)
age = input("Invalid age, please enter only integer value: ")

# loops forever until a valid OS is chosen
def preferred_os_input() -> OperatingSystem:
os_options = [member.name for member in OperatingSystem]
os_choice = input(f"Enter your preferred laptop from {os_options}: ").strip().upper()

while True:
if (os_choice in os_options):
return OperatingSystem[os_choice]
os_choice = input(f"Invalid choice, check spelling and spaces. choices: {os_options}: ").strip().upper()


print(f"Welcome to the CYF library. Enter your details to begin")

name = person_name_input()
age = person_age_input()
prefered_os = preferred_os_input()

person: Person = Person(name, age, prefered_os)

possible_laptops = find_possible_laptops(laptops, person)

print(f"There are {len(possible_laptops)} laptops with your preferred OS.")

# keep only non-preferred OS, and then see if there there is an OS with more laptops available
non_preferred_os = filter(lambda x: x.operating_system != person.preferred_operating_system, laptops)

counter = Counter(laptop.operating_system for laptop in non_preferred_os)
most_common_os, count = counter.most_common(1)[0]

if (count > len(possible_laptops)):
print(f"there are {count} latops with {most_common_os.name} operating system. You are more likely to get a laptop if you choose {most_common_os.name} ")
23 changes: 23 additions & 0 deletions sprint-5-exercises/person_class_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
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)

# Understand the errors from running mypy on this code

# Person_class_errors.py:9: error: "Person" has no attribute "address" [attr-defined]
# Because there is type definiton in the constructor of the Person class, mypy checks whether
# the imran object has an address attribute, and finds that it does not.

# Person_class_errors.py:13: error: "Person" has no attribute "address" [attr-defined]
# Same with eliza. It is a Person type object, without an address property, code attempts to
# print in line 13.
26 changes: 26 additions & 0 deletions sprint-5-exercises/person_datetime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# modify to use datetime.date to take in a date of birth
# store in a field instead of age
import datetime as dt

class Person:
def __init__(self, name: str, birthdate: dt.date, preferred_operating_system: str):
self.name = name
self.birthdate = birthdate
self.preferred_operating_system = preferred_operating_system
self.birthdate = birthdate

def is_adult(self) -> bool:
today = dt.date.today()
years = today.year - self.birthdate.year
# python does a lexicographical comparison of the elements in the tuples
# only checks the days if the months are equal

had_birthday_this_year = (today.month, today.day) >= (self.birthdate.month, self.birthdate.day)
age = years if had_birthday_this_year else years - 1
return age >= 18

# note: the above is necessary because with my old version, if the original birthday is on feb 29
# then it would try to create a new date of feb 29 on a non-leap year and crash

imran = Person("Imran", dt.date(2008,8,6), "Ubuntu")
print(imran.is_adult())
17 changes: 17 additions & 0 deletions sprint-5-exercises/predict_double.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def half(value):
return value / 2

def double(value):
return value * 2

def second(value):
return value[1]


# predict what double("22") will do

print(double("22"))

# I predict that the function will return "2222", as the * operator is overloaded in python.
# So that if a number is given, it performs the arithmetic operation, but if a string is given it just repeats
# the string 2 times
Loading
Loading