diff --git a/1.py b/1.py new file mode 100644 index 0000000..90c3e09 --- /dev/null +++ b/1.py @@ -0,0 +1,19 @@ +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 +# Fix version + +def triple(number): + return number * 3 + +print(triple(10)) + +# or + +def double(number): + return number * 2 + +print(double(10)) \ No newline at end of file diff --git a/2.py b/2.py new file mode 100644 index 0000000..3d37411 --- /dev/null +++ b/2.py @@ -0,0 +1,41 @@ +from typing import List, 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 = 0 + for name, pence in accounts.items(): + print(f"{name} had balance {pence}") + total += pence + return total + +def format_pence_as_str(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:int = sum_balances(balances) +total_string: str = format_pence_as_str(total_pence) + +print(f"The bank accounts total {total_string}") \ No newline at end of file diff --git a/3.py b/3.py new file mode 100644 index 0000000..9e548ef --- /dev/null +++ b/3.py @@ -0,0 +1,27 @@ +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) + +# error: "Person" has no attribute "address" +# error: "Person" has no attribute "address" + +def is_adult(person: Person) -> bool: + return person.age >= 18 + +print(is_adult(imran)) +# no error + + +def get_city(person: Person) -> str: + return person.location +#person has no attribute location. \ No newline at end of file diff --git a/4.py b/4.py new file mode 100644 index 0000000..a28d2c8 --- /dev/null +++ b/4.py @@ -0,0 +1,18 @@ +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(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 + +imran_dob = date(2003, 9, 10) +imran = Person("Imran", imran_dob, "Ubuntu") + +print(is_adult(imran)) # True \ No newline at end of file diff --git a/5.py b/5.py new file mode 100644 index 0000000..9e3af7a --- /dev/null +++ b/5.py @@ -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: + 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 \ No newline at end of file diff --git a/6.py b/6.py new file mode 100644 index 0000000..28057ed --- /dev/null +++ b/6.py @@ -0,0 +1,27 @@ +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) + +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]) + +print_family_tree(imran) \ No newline at end of file diff --git a/7.py b/7.py new file mode 100644 index 0000000..265cac4 --- /dev/null +++ b/7.py @@ -0,0 +1,41 @@ +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}") \ No newline at end of file diff --git a/8.py b/8.py new file mode 100644 index 0000000..a4a76e1 --- /dev/null +++ b/8.py @@ -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() \ No newline at end of file diff --git a/9.py b/9.py new file mode 100644 index 0000000..ed7a4f1 --- /dev/null +++ b/9.py @@ -0,0 +1,49 @@ +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()) + + +#W/O commenting output: +#Elizaveta Alekseeva +#Elizaveta Alekseeva +#Elizaveta Tyurina +#Elizaveta Alekseeva +#Elizaveta Tyurina (née Alekseeva) +#Traceback (most recent call last): +# File "/Users/Module-Decomposition/prep_exercises/exercise9inheritance.py", line 34, in +# print(person2.get_full_name()) +#AttributeError: 'Parent' object has no attribute 'get_full_name' \ No newline at end of file