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

#enum exersice

from dataclasses import dataclass
from typing import List
import sys


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


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


laptops = [
Laptop(1, "Dell", "XPS", 13, "Ubuntu"),
Laptop(2, "Dell", "XPS", 15, "Ubuntu"),
Laptop(3, "Dell", "XPS", 15, "Arch Linux"),
Laptop(4, "Apple", "MacBook", 13, "macOS"),
Laptop(5, "Lenovo", "ThinkPad", 14, "Ubuntu"),
]


name = input("Enter your name: ")

try:
age = int(input("Enter your age: "))
except ValueError:
print("Error: age must be a number.", file=sys.stderr)
sys.exit(1)


preferred_operating_system = input(
"Enter your preferred operating system: "
)

available_operating_systems = {
laptop.operating_system for laptop in laptops
}

if preferred_operating_system not in available_operating_systems:
print(
"Error: that operating system is not available.",
file=sys.stderr
)
sys.exit(1)


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


matching_laptops = [
laptop
for laptop in laptops
if laptop.operating_system == person.preferred_operating_system
]

print(
f"The library has {len(matching_laptops)} "
f"laptop(s) with {person.preferred_operating_system}."
)


laptop_counts = {}

for laptop in laptops:
laptop_counts[laptop.operating_system] = (
laptop_counts.get(laptop.operating_system, 0) + 1
)


for operating_system, count in laptop_counts.items():
if (
operating_system != person.preferred_operating_system
and count > len(matching_laptops)
):
print(
f"The library has more {operating_system} laptops "
f"({count}). You are more likely to get a laptop "
f"if you are willing to use {operating_system}."
)
27 changes: 27 additions & 0 deletions Sprint-5/Exersice1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

# Predict what double("22") will do. Then run the code and check. Did it do what you expected? Why did it return the value it did?


# double("22") returns "2222".

# "22" is a string, so * 2 repeats the string twice.


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"))

print(second(22))
print(second(0x16))
print(second("hello"))
print(second("22"))

51 changes: 51 additions & 0 deletions Sprint-5/Exersice11.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Inheritance exercise.

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())

# Parent does not have get_full_name()
# print(person2.get_full_name())

# Parent does not have change_last_name()
# person2.change_last_name("Tyurina")

# These would work if the above line was not an error:
# print(person2.get_name())
# print(person2.get_full_name())
13 changes: 13 additions & 0 deletions Sprint-5/Exersice2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

# Read the above code and write down what the bug is. How would you fix it?

# The bug was that the function multiplied the number by 3.

# Since the function is called double, it should multiply the number by 2.

def double(number):
return number * 2

print(double(10))


53 changes: 53 additions & 0 deletions Sprint-5/Exersice3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# type checking

rom 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,
}

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}")

# Answer:

# The type annotations tell mypy what types are expected.

# balances contains string names and integer balances.

# The account amounts are stored as pence, so £9.13 is 913

# and £7.13 is 713.

# format_pence_as_string returns a string.

# The original function call had the wrong function name:

# format_pence_as_str -> format_pence_as_string
36 changes: 36 additions & 0 deletions Sprint-5/Exersice4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Classes and objects

# Classes and objects

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

# there is an error because the is_developer attribute is not in the Person class.
12 changes: 12 additions & 0 deletions Sprint-5/Exersice5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# methods

# Think of the advantages of using methods

Encapsulation:
Data and methods are kept together in one class, which controls how the data can be accessed or changed. It hides the implementation details and allows the implementation to change without affecting the user, as long as the interface stays the same.
For example, a Person class can control how a person's data is modified.


Ease of use:
Users only need to know how to use the class's interface, not how it works internally. Methods can be easily accessed using dot notation and IDE autocomplete,
for example person.is_adult().
19 changes: 19 additions & 0 deletions Sprint-5/Exersice6.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@

# Change the Person class to take a date of birth (using the standard library’s datetime.date class) and store it 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()
print(today)
return today >= dt.date(self.birthdate.year +18, self.birthdate.month, self.birthdate.day)

imran = Person("Imran", dt.date(2008,8,6), "Ubuntu")
print(imran.is_adult())
35 changes: 35 additions & 0 deletions Sprint-5/Exersice7.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

# Write a Person class using @datatype which uses a datetime.date for date of birth, rather than an int for age.

from dataclasses import dataclass
from datetime import date


@dataclass
class Person:
name: str
date_of_birth: date
preferred_operating_system: str

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

years = today.year - self.date_of_birth.year

had_birthday_this_year = (
(today.month, today.day)
>= (self.date_of_birth.month, self.date_of_birth.day)
)

age = years if had_birthday_this_year else years - 1

return age >= 18


imran = Person(
"Imran",
date(2008, 8, 6),
"Ubuntu"
)

print(imran.is_adult())
26 changes: 26 additions & 0 deletions Sprint-5/Exersice8.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Generic exersice

from dataclasses import dataclass
from typing import List


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


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

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


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)
Loading
Loading