diff --git a/Sprint5/exercise1.py b/Sprint5/exercise1.py new file mode 100644 index 000000000..c362071a5 --- /dev/null +++ b/Sprint5/exercise1.py @@ -0,0 +1,3 @@ +# 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. \ No newline at end of file diff --git a/Sprint5/exercise10.py b/Sprint5/exercise10.py new file mode 100644 index 000000000..41308a5ed --- /dev/null +++ b/Sprint5/exercise10.py @@ -0,0 +1,89 @@ +#Try changing the type annotation of Person.preferred_operating_system from str to List[str]. +#Run mypy on the code. +#It tells us different places that our code is now wrong, because we’re passing values of the wrong type. +#We probably also want to rename our field - lists are plural. Rename the field to preferred_operating_systems. +#Run mypy again. +#Fix all of the places that mypy tells you need changing. Make sure the program works as you’d expect. + +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: + if laptop.operating_system in person.preferred_operating_systems: + 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", "macOS"] + ), +] + + +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}") diff --git a/Sprint5/exercise11.py b/Sprint5/exercise11.py new file mode 100644 index 000000000..8ee8ea1b1 --- /dev/null +++ b/Sprint5/exercise11.py @@ -0,0 +1,143 @@ +#Write a program which: + +#Already has a list of Laptops that a library has to lend out. +#Accepts user input to create a new Person - it should use the input function to read a person’s name, age, and preferred operating system. +#Tells the user how many laptops the library has that have that operating system. +#If there is an operating system that has more laptops available, tells the user that if they’re willing to accept that operating system they’re more likely to get a laptop. +#You should convert the age and preferred operating system input from the user into more constrained types as quickly as possible, and should output errors to stderr and terminate the program with a non-zero exit code if the user input bad values. + +from dataclasses import dataclass +from enum import Enum +from typing import List +import sys + + +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 + + +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, + ), +] + + +name = input("What is your name? ") + +try: + age = int(input("What is your age? ")) +except ValueError: + print("Error: age must be a number.", file=sys.stderr) + sys.exit(1) + + +print("Available operating systems:") +for operating_system in OperatingSystem: + print(f"- {operating_system.value}") + +preferred_os_input = input("What is your preferred operating system? ") + +try: + preferred_operating_system = OperatingSystem(preferred_os_input) +except ValueError: + print( + f"Error: '{preferred_os_input}' is not a valid operating system.", + file=sys.stderr, + ) + sys.exit(1) + + +person = Person( + name=name, + age=age, + preferred_operating_system=preferred_operating_system, +) + + +possible_laptops = find_possible_laptops(laptops, person) + +print( + f"The library has {len(possible_laptops)} " + f"laptop(s) with {person.preferred_operating_system.value}." +) + + +laptop_counts = {} + +for laptop in laptops: + laptop_counts[laptop.operating_system] = ( + laptop_counts.get(laptop.operating_system, 0) + 1 + ) + +most_available_os = max( + laptop_counts, + key=laptop_counts.get +) + + +if ( + most_available_os != person.preferred_operating_system + and laptop_counts[most_available_os] > len(possible_laptops) +): + print( + f"There are more {most_available_os.value} laptops available. " + f"If you're willing to accept {most_available_os.value}, " + f"you're more likely to get a laptop." + ) \ No newline at end of file diff --git a/Sprint5/exercise12.py b/Sprint5/exercise12.py new file mode 100644 index 000000000..89a269db9 --- /dev/null +++ b/Sprint5/exercise12.py @@ -0,0 +1,57 @@ +person1 = Child("Elizaveta", "Alekseeva") +# Prediction: Creates instance of Child class with first name "Elizaveta" and last name "Alekseeva". +print(person1) +print(person1.first_name) +print(person1.last_name) +# Outcome: As expected. + + +print(person1.get_name()) +# Prediction: Child inherits Parent methods, therefore calls get_name method: "Elizaveta Alekseeva" +# Outcome: As expected. + +print(person1.get_full_name()) +# Prediction: Calls get_full_name on child, no previous names: "Elizaveta Alekseeva" +# Outcome: As expected. + +person1.change_last_name("Tyurina") +# Prediction: Changes last_name to "Tyurina", and previous_last_names to ["Alekseeva"], returns nothing +print(person1.last_name) +print(person1.previous_last_names) +# Outcome: As expected. + +print(person1.get_name()) +# Prediction: Child inherits Parent methods, therefore calls get_name method: "Elizaveta Alekseeva" +# Outcome: As expected. + +print(person1.get_full_name()) +# Prediction: Returns first_name last_name (née previous_last_names[0]) (original last name) +# ""Elizaveta Tyurina (née Alekseeva)" +# Outcome: As expected. + +person2 = Parent("Elizaveta", "Alekseeva") +# Prediction: Creates instance of Parent class with first name "Elizaveta" and last name "Alekseeva". +print(person2) +print(person2.first_name) +print(person2.last_name) +# Outcome: As expected. + +print(person2.get_name()) +# Prediction: Calls get_name method: "Elizaveta Alekseeva" +# Outcome: As expected. + +# print(person2.get_full_name()) +# Prediction: Parent instance has not access to Child methods, will error that there is no method of get_full_name. +# Outcome: AttributeError: 'Parent' object has no attribute 'get_full_name' + +# person2.change_last_name("Tyurina") +# Prediction: Parent instance has not access to Child methods, will error that there is no method of change_last_name. +# Outcome: AttributeError: 'Parent' object has no attribute 'change_last_name' + +print(person2.get_name()) +# Prediction: Calls get_name method: "Elizaveta Alekseeva" as name has not changed due to inability to call change_last_name +# Outcome: As expected. + +# print(person2.get_full_name()) +# Prediction: Parent instance has not access to Child methods, will error that there is no method of get_full_name. +# Outcome: AttributeError: 'Parent' object has no attribute 'get_full_name' \ No newline at end of file diff --git a/Sprint5/exercise2.py b/Sprint5/exercise2.py new file mode 100644 index 000000000..74218ec9a --- /dev/null +++ b/Sprint5/exercise2.py @@ -0,0 +1,12 @@ +def double(number): + return number * 3 + +print(double(10)) + +# Read the above code and write down what the bug is. How would you fix it? +# Since the function is called double, it should multiply the number by 2. + +def double(number): + return number * 2 + +print(double(10)) diff --git a/Sprint5/exercise3.py b/Sprint5/exercise3.py new file mode 100644 index 000000000..a5b09f1fd --- /dev/null +++ b/Sprint5/exercise3.py @@ -0,0 +1,36 @@ +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 = (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}") + diff --git a/Sprint5/exercise4.py b/Sprint5/exercise4.py new file mode 100644 index 000000000..97e2a8a9d --- /dev/null +++ b/Sprint5/exercise4.py @@ -0,0 +1,17 @@ +class Person: + def __init__( + self, + name: str, + age: int, + preferred_operating_system: str, + address: str + ): + self.name = name + self.age = age + self.preferred_operating_system = preferred_operating_system + self.address = address + +imran = Person("Imran",22,"Ubuntu","Sheffield") +print(imran.address) + +#mypy knows what attributes a Person object is supposed to have. If you try to access an attribute that isn't defined in the class, mypy can warn you before you run the program.Adress needed to define in person object for print. \ No newline at end of file diff --git a/Sprint5/exercise5.py b/Sprint5/exercise5.py new file mode 100644 index 000000000..00675130d --- /dev/null +++ b/Sprint5/exercise5.py @@ -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) + +eliza = Person("Eliza", 34, "Arch Linux") +print(eliza.name) + + +def is_adult(person: Person) -> bool: + return person.age >= 18 + + +print(is_adult(imran)) + + +def get_address(person: Person) -> str: + return person.address \ No newline at end of file diff --git a/Sprint5/exercise6.py b/Sprint5/exercise6.py new file mode 100644 index 000000000..3a05a288d --- /dev/null +++ b/Sprint5/exercise6.py @@ -0,0 +1,10 @@ +#Think of the advantages of using methods instead of free functions. Write them down in your notebook. + + +#Advantages of methods over free functions: + +#Methods keep related data and behaviour together. +#They make code easier to read and understand. +#They can directly access an object's attributes using self. +#They make it clear which object is performing an action. +#They help organise and maintain larger programs. diff --git a/Sprint5/exercise7.py b/Sprint5/exercise7.py new file mode 100644 index 000000000..dd7bbddde --- /dev/null +++ b/Sprint5/exercise7.py @@ -0,0 +1,21 @@ +#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. +#Update the is_adult method to act the same as before. + +from datetime import date + + +class Person: + def __init__(self, date_of_birth: date): + self.date_of_birth = date_of_birth + + def is_adult(self) -> bool: + today = date.today() + age = today.year - self.date_of_birth.year + + if (today.month, today.day) < ( + self.date_of_birth.month, + self.date_of_birth.day, + ): + age -= 1 + + return age >= 18 \ No newline at end of file diff --git a/Sprint5/exercise8.py b/Sprint5/exercise8.py new file mode 100644 index 000000000..04b084db5 --- /dev/null +++ b/Sprint5/exercise8.py @@ -0,0 +1,25 @@ +#Write a Person class using @datatype which uses a datetime.date for date of birth, rather than an int for age. + +#Re-add the is_adult method to it. + +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() + age = today.year - self.date_of_birth.year + + if (today.month, today.day) < ( + self.date_of_birth.month, + self.date_of_birth.day, + ): + age -= 1 + + return age >= 18 \ No newline at end of file diff --git a/Sprint5/exercise9.py b/Sprint5/exercise9.py new file mode 100644 index 000000000..8510a5917 --- /dev/null +++ b/Sprint5/exercise9.py @@ -0,0 +1,26 @@ +#Fix the above code so that it works. You must not change the print on line 17 - we do want to print the children’s ages. (Feel free to invent the ages of Imran’s children.) + +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=3, children=[]) + +imran = Person(name="Imran", age=30, 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) \ No newline at end of file