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
1 change: 1 addition & 0 deletions introduction-to-typescript
Submodule introduction-to-typescript added at f8d3a1
18 changes: 18 additions & 0 deletions sprint-5-prep/classes-and-objects-and-methods.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from datetime import date

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

def is_adult(self) -> bool:
today = date.today()
eighteen_years_ago = date(today.year - 18, today.month, today.day)
return self.dOB <= eighteen_years_ago

imran = Person("Imran", date(1992, 7, 21), "Ubuntu")
print(imran.name)

print(imran.is_adult())

26 changes: 26 additions & 0 deletions sprint-5-prep/dataclasses-chapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from dataclasses import dataclass
from datetime import date

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

def is_adult(self) -> bool:
today = date.today()
eighteen_years_ago = date(today.year - 18, today.month, today.day)
return self.DOB <= eighteen_years_ago

imran = Person("Imran", date(1992, 7, 21), "Ubuntu")
print(imran.name)

imran2 = Person("Imran", date(1992, 7, 21), "Ubuntu")
print(imran == imran2)

eliza = Person("Eliza", date(1982, 4, 5), "Arch Linux")
print(eliza.name)


print(imran.is_adult())
print(eliza.is_adult())
81 changes: 81 additions & 0 deletions sprint-5-prep/enums-chapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import sys
from sys import stderr
from dataclasses import dataclass
from enum import Enum
from typing import List

class OperatingSystem(Enum):
MACOS = "macos"
ARCH = "arch linux"
UBUNTU = "ubuntu"

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

@dataclass(frozen=True)
class Person:
name: str
age: int
preferred_operating_system: OperatingSystem

available_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),
Laptop(id=5, manufacturer="HP", model="Spectre", screen_size_in_inches=13, operating_system=OperatingSystem.UBUNTU),
Laptop(id=6, manufacturer="Lenovo", model="ThinkPad", screen_size_in_inches=14, operating_system=OperatingSystem.ARCH),
Laptop(id=7, manufacturer="Apple", model="MacBook Pro", screen_size_in_inches=16, operating_system=OperatingSystem.MACOS),
Laptop(id=8, manufacturer="Dell", model="Inspiron", screen_size_in_inches=15, operating_system=OperatingSystem.UBUNTU),
Laptop(id=9, manufacturer="Asus", model="ZenBook", screen_size_in_inches=13, operating_system=OperatingSystem.ARCH),
]



def error_exit(message: str, code: int =1) -> None:
print(f"Error: {message}", file=stderr)
sys.exit(code)

def number_of_laptops_per_os() -> dict[OperatingSystem, int]:
os_count: dict[OperatingSystem, int] = {
OperatingSystem.MACOS: 0,
OperatingSystem.ARCH: 0,
OperatingSystem.UBUNTU: 0,
}
for laptop in available_laptops:
os_count[laptop.operating_system] += 1
return os_count

def main() -> None:
name: str = input("Enter your name: ").strip()
if not name:
error_exit("Name cannot be empty.")

try:
age: int = int(input("Enter your age: ").strip())
if age <= 0:
error_exit("Age must be a positive integer.")
except ValueError:
error_exit("Invalid age. Please enter a positive integer.")

try:
preferred_operating_system: OperatingSystem = OperatingSystem(input("Enter your preferred operating system (macOS, Arch Linux, Ubuntu): ").strip().lower())
except ValueError:
error_exit("Invalid operating system. Choose from macOS, Arch Linux, Ubuntu.")

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

os_count = number_of_laptops_per_os()
print(f"Hi {person.name}, there are {os_count[preferred_operating_system]} laptops available with {preferred_operating_system.value}.")
max_os, max_count = max(os_count.items(), key=lambda item: item[1])
print(f"The operating system with the most laptops is {max_os.value} with {max_count} laptops.")
print ("person:", person)


if __name__ == "__main__":
main()
19 changes: 19 additions & 0 deletions sprint-5-prep/generics-chapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from dataclasses import dataclass

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

fatma = Person(name="Fatma", children=[], age=5)
aisha = Person(name="Aisha", children=[], age=3)

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

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)
28 changes: 28 additions & 0 deletions sprint-5-prep/how-we-use-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
```python
def half(value):
return value / 2

def double(value):
return value * 2

def second(value):
return value[1]

print(double(22))
print(double("hello"))
print(double("22"))
```
# Exercise 1:

Prediction:
double("22") will raise a typeError because "22" is a string.

Actual Result:
double ("22") actually returned "2222" so it actually resulted in a string repetition "2222"
this shows that the '*2' sign on strings will repeat them

# Exercise 2:

the bug on the code is the naming of the function. you can't call a function double() but then
the math is [value *3]. so we should either rename it triple() or change the method to [value *2]
depending on the context and what we are trying to achieve.
37 changes: 37 additions & 0 deletions sprint-5-prep/inheritance-chapter.py
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())
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())
# person2.change_last_name("Tyurina")
print(person2.get_name())
# print(person2.get_full_name())
30 changes: 30 additions & 0 deletions sprint-5-prep/type-checking-with-mypy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def open_account(balances: dict[str, int], name: str, amount: float) -> None:
balances[name] = int(amount*100)

def sum_balances(accounts: dict[str, int]) -> int:
total = 0
for name, pence in accounts.items():
print(f"{name} had balance {pence}p")
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,
}

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

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

print(f"The bank accounts total {total_string}")
43 changes: 43 additions & 0 deletions sprint-5-prep/type-guided-refactoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
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 = []
for laptop in laptops:
for os in person.preferred_operating_systems:
if laptop.operating_system == os:
possible_laptops.append(laptop)
return possible_laptops


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