-
-
Notifications
You must be signed in to change notification settings - Fork 105
London | 26-ITP-July | Raihan Sharif | Sprint 5 | Prep Exercises #651
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
RaihanSharif
wants to merge
17
commits into
CodeYourFuture:main
Choose a base branch
from
RaihanSharif:sprint-5-prep-execises
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
c8c82a9
predict double
RaihanSharif 1ffae14
fix double
RaihanSharif bb92289
Add type annotation to bank account
RaihanSharif daa4e3f
explain mypy errors in Person class file
RaihanSharif 75ccf6d
is_adult type check
RaihanSharif 3f15834
advantages of methods
RaihanSharif 51aa7d6
datetime birthday
RaihanSharif 9044ad5
account for leap year
RaihanSharif 6f51289
remove dead code
RaihanSharif cf25708
convert Person to dataclass
RaihanSharif ca600fa
generics - children age
RaihanSharif 6a8dc0c
refactor: latop preferences is a list
RaihanSharif d03702f
create valid user from input
RaihanSharif 5eb94f1
show user laptop choices
RaihanSharif 2c28a27
inheritance predictions
RaihanSharif b735ff2
Removed dead code after code review
RaihanSharif 70a56c3
fix spelling mistake
RaihanSharif File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
|
|
||
|
|
||
| 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)) | ||
|
|
||
| # As expected, there is an error because the is_developer attribute is not present in the Person class. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| Encapsulation: | ||
| Data and methods are packaged together to form one cohesive unit. | ||
| This allows great control of access and modification of the data, | ||
| presenting an interface to the user, and hiding the implementation details. | ||
|
|
||
| The class/object can impose rules on access and modification. E.g. balance can't | ||
| be negative. | ||
|
|
||
| Implementation can also be changed without breaking the interface which | ||
| should be reliable and consistent over time. | ||
|
|
||
| Ease of use: | ||
| Makes it easier for users of the data, as they only need to reason about | ||
| the interface, not the implementation details. E.g. methods that operate on an object | ||
| can be easily with the dot notation and IDE autocomplete. | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| 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, | ||
| } | ||
|
|
||
| # the amount is int pence not float pounds | ||
| 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}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # convert person class to a dataclass | ||
| import datetime as dt | ||
| from dataclasses import dataclass | ||
|
|
||
| @dataclass | ||
| class Person: | ||
| name: str | ||
| birthdate: dt.date | ||
| preferred_operating_system: str | ||
|
|
||
| def is_adult(self) -> bool: | ||
| today = dt.date.today() | ||
| years = today.year - self.birthdate.year | ||
| # python does a lexicographical comparison of the elements in the tuples | ||
| # only checks the days if the months are equal | ||
|
|
||
| had_birthday_this_year = (today.month, today.day) >= (self.birthdate.month, self.birthdate.day) | ||
| age = years if had_birthday_this_year else years - 1 | ||
| return age >= 18 | ||
|
|
||
| # note: the above is necessary because with my old version, if the original birthday is on feb 29 | ||
| # then it would try to create a new date of feb 29 on a non-leap year and crash | ||
|
|
||
| imran = Person("Imran", dt.date(2009,8,6), "Ubuntu") | ||
| print(imran.is_adult()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| def double(number): | ||
| # return number * 3 | ||
| return number * 2. # the fix | ||
|
|
||
| print(double(10)) | ||
|
|
||
| # bug: function is called double, but returns tripple of what is given as input. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| from dataclasses import dataclass | ||
| from typing import List | ||
|
|
||
| @dataclass(frozen=True) | ||
| class Person: | ||
| name: str | ||
| children: List["Person"] | ||
| age: int | ||
|
|
||
| fatma = Person(name="Fatma", children=[], age=12) | ||
| aisha = Person(name="Aisha", children=[], age=15) | ||
|
|
||
| imran = Person(name="Imran", children=[fatma, aisha], age=40) | ||
|
|
||
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
|
|
||
| # parent class has two string fields, first_name, last_name | ||
| # a method that return a string which joins the two names with a space | ||
| 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}" | ||
|
|
||
|
|
||
| # extends parent class | ||
| # add ability to change last name, store previous last names in a list | ||
| # a method that prints first and last name as well as the original last name of Child | ||
| 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()) # inherit from Parent class, output = "Elizaveta Alekseeva" | ||
| print(person1.get_full_name()) # method of Child class, output = "Elizaveta Alekseeva" no previous surname | ||
| person1.change_last_name("Tyurina") # changes last name of person1, adds "Alekseeva" to previous names list | ||
| print(person1.get_name()) # last name has changed, output = "Elizaveta Tyurina" | ||
| print(person1.get_full_name()) # includes maiden name, output = "Elizaveta Tyurina (née Alekseeva)" | ||
|
|
||
| person2 = Parent("Elizaveta", "Alekseeva") | ||
| print(person2.get_name()) # output = "Elizaveta Alekseeva" | ||
| print(person2.get_full_name()) # AttrbuteError - the Parent class does not have get_full_name() method | ||
| person2.change_last_name("Tyurina") # same again | ||
| print(person2.get_name()) # no problems, same as line 40 | ||
| print(person2.get_full_name()) # again, no get_full_name() method in this Parent class. Same as line 41 |
|
RaihanSharif marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| 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" | ||
|
|
||
| @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), | ||
| ] | ||
|
|
||
|
|
||
| # take input (name, age, preferred os), create Person object | ||
| # show them how many laptops with their chosen OS are available | ||
| # if there is a different os with more laptops, tell user they are more likely to get a laptop | ||
| # if they choose that os | ||
|
|
||
| # loops forever until alphabetic string provided | ||
| def person_name_input() -> str: | ||
| name = input("Enter your first name: ") | ||
| while True: | ||
| if (name.isalpha()): | ||
| return name | ||
| name = input("invalid first name, please enter only letters: ") | ||
|
|
||
| # loops forever until numeric input is provided | ||
| def person_age_input() -> int: | ||
| age = input("Enter your age: ") | ||
| while True: | ||
| if (age.isnumeric()): | ||
| return int(age) | ||
| age = input("Invalid age, please enter only integer value: ") | ||
|
|
||
| # loops forever until a valid OS is chosen | ||
| def preferred_os_input() -> OperatingSystem: | ||
| os_options = [member.name for member in OperatingSystem] | ||
| os_choice = input(f"Enter your preferred laptop from {os_options}: ").strip().upper() | ||
|
|
||
| while True: | ||
| if (os_choice in os_options): | ||
| return OperatingSystem[os_choice] | ||
| os_choice = input(f"Invalid choice, check spelling and spaces. choices: {os_options}: ").strip().upper() | ||
|
|
||
|
|
||
| print(f"Welcome to the CYF library. Enter your details to begin") | ||
|
|
||
| name = person_name_input() | ||
| age = person_age_input() | ||
| preferred_os = preferred_os_input() | ||
|
|
||
| person: Person = Person(name, age, preferred_os) | ||
|
|
||
| possible_laptops = find_possible_laptops(laptops, person) | ||
|
|
||
| print(f"There are {len(possible_laptops)} laptops with your preferred OS.") | ||
|
|
||
| # keep only non-preferred OS, and then see if there there is an OS with more laptops available | ||
| non_preferred_os = filter(lambda x: x.operating_system != person.preferred_operating_system, laptops) | ||
|
|
||
| counter = Counter(laptop.operating_system for laptop in non_preferred_os) | ||
| most_common_os, count = counter.most_common(1)[0] | ||
|
|
||
| if (count > len(possible_laptops)): | ||
| print(f"there are {count} latops with {most_common_os.name} operating system. You are more likely to get a laptop if you choose {most_common_os.name} ") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| print(imran.address) | ||
|
|
||
| eliza = Person("Eliza", 34, "Arch Linux") | ||
| print(eliza.name) | ||
| print(eliza.address) | ||
|
|
||
| # Understand the errors from running mypy on this code | ||
|
|
||
| # Person_class_errors.py:9: error: "Person" has no attribute "address" [attr-defined] | ||
| # Because there is type definiton in the constructor of the Person class, mypy checks whether | ||
| # the imran object has an address attribute, and finds that it does not. | ||
|
|
||
| # Person_class_errors.py:13: error: "Person" has no attribute "address" [attr-defined] | ||
| # Same with eliza. It is a Person type object, without an address property, code attempts to | ||
| # print in line 13. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| # modify to use datetime.date to take in a date of birth | ||
| # store 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() | ||
| years = today.year - self.birthdate.year | ||
| # python does a lexicographical comparison of the elements in the tuples | ||
| # only checks the days if the months are equal | ||
|
|
||
| had_birthday_this_year = (today.month, today.day) >= (self.birthdate.month, self.birthdate.day) | ||
| age = years if had_birthday_this_year else years - 1 | ||
| return age >= 18 | ||
|
|
||
| # note: the above is necessary because with my old version, if the original birthday is on feb 29 | ||
| # then it would try to create a new date of feb 29 on a non-leap year and crash | ||
|
|
||
| imran = Person("Imran", dt.date(2008,8,6), "Ubuntu") | ||
| print(imran.is_adult()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| def half(value): | ||
| return value / 2 | ||
|
|
||
| def double(value): | ||
| return value * 2 | ||
|
|
||
| def second(value): | ||
| return value[1] | ||
|
|
||
|
|
||
| # predict what double("22") will do | ||
|
|
||
| print(double("22")) | ||
|
|
||
| # I predict that the function will return "2222", as the * operator is overloaded in python. | ||
| # So that if a number is given, it performs the arithmetic operation, but if a string is given it just repeats | ||
| # the string 2 times |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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_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}") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good explanations