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
23 changes: 23 additions & 0 deletions 1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
def double(number):
return number * 3

print(double(10))


"""
Here the name of the function is double but on line 3 it returns the triple of the a given number
"""

#Ideal solutions:

def triple(number):
return number * 3

print(double(10))

"or"

def double(number):
return number * 2

print(double(10))
42 changes: 42 additions & 0 deletions 2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from typing import Dict, Union

def open_account(balances: Dict[str, int], name: str, amount: Union[int, float, str]) -> None:
if isinstance(amount, str) and amount.startswith("£"):
pounds, pence = map(int, amount[1:].split("."))
amount = pounds * 100 + pence
elif isinstance(amount, float):
amount = int(round(amount * 100))
elif isinstance(amount, int):
pass
else:
raise ValueError("Unsupported amount format")
balances[name] = amount

def sum_balances(accounts: Dict[str, int]) -> int:
total: int = 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: int = total_pence % 100
return f"£{pounds}.{pence:02d}"

# Main block
balances: Dict[str, int] = {
"Sima": 700,
"Linn": 545,
"Georg": 831,
}

open_account(balances, "Tobi", 9.13) # float input
open_account(balances, "Olya", "£7.13") # string input

total_pence: int = sum_balances(balances)
total_string: str = format_pence_as_string(total_pence)

print(f"The bank accounts total {total_string}")
47 changes: 47 additions & 0 deletions 3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
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,
}

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

# Person class
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

Choose a reason for hiding this comment

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

did you try running the code and spotting what the error was?


imran = Person("Imran", 22, "Ubuntu")

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

print(is_adult(imran)) # Output: True
53 changes: 53 additions & 0 deletions 4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from typing import Dict
from datetime import date

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

# Updated Person class
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

# Updated is_adult function
def is_adult(person: Person) -> bool:
today = date.today()
dob = person.date_of_birth
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
return age >= 18

# Example usage
imran_dob = date(2003, 9, 10)
imran = Person("Imran", imran_dob, "Ubuntu")

print(is_adult(imran)) # Output: True
19 changes: 19 additions & 0 deletions 5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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:

Choose a reason for hiding this comment

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

What is a benefit or drawback of writing the function this way?

today = date.today()
dob = self.date_of_birth
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
return age >= 18


imran = Person(name="Imran", date_of_birth=date(2003, 9, 10), preferred_operating_system="Ubuntu")

print(imran.is_adult()) # Output: True
29 changes: 29 additions & 0 deletions 6.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from dataclasses import dataclass
from datetime import date
from typing import List

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

@property
def age(self) -> int:
today = date.today()
dob = self.date_of_birth
return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))

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

# Sample data
fatma = Person(name="Fatma", date_of_birth=date(2012, 5, 14), children=[])
aisha = Person(name="Aisha", date_of_birth=date(2015, 8, 3), children=[])
imran = Person(name="Imran", date_of_birth=date(1985, 2, 20), children=[fatma, aisha])

# Output family tree
print_family_tree(imran)
42 changes: 42 additions & 0 deletions 7.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_systems: List[str]


def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]:
possible_laptops = []
for laptop in laptops:
if laptop.operating_systems == 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_systems=["Arch Linux"]),
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_systems=["Ubuntu"]),
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_systems=["ubuntu"]),
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_systems=["macOS"]),
]

for person in people:
possible_laptops = find_possible_laptops(laptops, person)
print(f"Possible laptops for {person.name}: {possible_laptops}")
88 changes: 88 additions & 0 deletions laptop_allocation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import sys
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"

@classmethod
def from_string(cls, s: str):
for os in cls:
if os.value.lower() == s.lower():
return os
raise ValueError(f"Unsupported operating system: {s}")


@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]:
return [laptop for laptop in laptops if laptop.operating_system == person.preferred_operating_system]


def main():
# Existing inventory
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),
]

# Read and validate user input
try:
name = input("Enter your name: ").strip()
if not name:
raise ValueError("Name cannot be empty.")

age_input = input("Enter your age: ").strip()
age = int(age_input)
if age <= 0:
raise ValueError("Age must be a positive integer.")

print("Available operating systems:")
for os in OperatingSystem:
print(f"- {os.value}")
os_input = input("Enter your preferred operating system: ").strip()
preferred_os = OperatingSystem.from_string(os_input)

except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)

# Create the person
person = Person(name=name, age=age, preferred_operating_system=preferred_os)

# Check availability
possible_laptops = find_possible_laptops(laptops, person)
print(f"\nThere are {len(possible_laptops)} laptops available with {preferred_os.value}.")

# Count OS distribution
os_counts = Counter(laptop.operating_system for laptop in laptops)
most_common_os, most_common_count = os_counts.most_common(1)[0]

if most_common_os != preferred_os and most_common_count > len(possible_laptops):
print(f"Note: There are more laptops available with {most_common_os.value} ({most_common_count} total).")
print(f"If you're willing to accept {most_common_os.value}, you're more likely to get a laptop.")


if __name__ == "__main__":
main()