├── 2020-06-28-python-tdd ├── __init__.py ├── eshopv2.py └── test_eshopv2.py ├── 2020-05-17-python-pytest ├── examples │ ├── __init__.py │ ├── code.py │ ├── test_code.py │ ├── e_shop.py │ └── test_e_shop.py └── homework │ └── one_number_bingo.py ├── 2020-06-14-python-property-based-testing ├── __init__.py ├── test_demo.py ├── test_dateutil_parser.py └── demo.py ├── 2020-04-12-python-basics ├── lazy_self_intro.py └── loan_calculator.py ├── 2020-08-03-python-docs ├── my_ops.py └── using_my_ops.ipynb ├── 2020-04-19-python-basics-2 ├── homework │ ├── exam_report.py │ └── combine_shopping.py └── examples │ ├── shopping_checkout.py │ └── family_checker.py ├── 2020-05-10-python-classes ├── homework │ └── one_number_bingo.py └── examples │ ├── demo.py │ └── e-shop.py ├── 2020-04-26-python-flow-control ├── homework │ └── one_number_bingo.py └── examples │ ├── random_fruit.py │ └── combine_checkout.py ├── 2020-05-03-python-functions ├── homework │ └── one_number_bingo.py └── examples │ ├── checkout_sum.py │ ├── random_fruit.py │ └── combine_checkout.py ├── 2020-05-24-python-decorators └── examples │ ├── demo.py │ ├── greeting_w_jokes.py │ └── e-shop.py ├── README.md ├── LICENSE ├── .gitignore ├── 2020-05-31-python-strings-regex └── examples │ └── e-shop.py ├── 2020-06-21-python-linting └── examples │ └── e-shop.py ├── 2020-07-26-python-async └── async.ipynb ├── 2020-07-19-python-generators └── generators.ipynb ├── 2020-08-23-python-functional.ipynb ├── 2020-09-06-python-os-subprocess.ipynb ├── 2020-08-30-more-python-list-dict.ipynb └── 2020-07-12-python-iterator └── iterators.ipynb /2020-06-28-python-tdd/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /2020-05-17-python-pytest/examples/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /2020-06-14-python-property-based-testing/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /2020-04-12-python-basics/lazy_self_intro.py: -------------------------------------------------------------------------------- 1 | name = 'Lais' 2 | pronoun = 'She/her' 3 | favourite = 'Chocolate' 4 | 5 | print(f"I am {name}, my pronoun is {pronoun}, and my favourite thing is {favourite}") 6 | -------------------------------------------------------------------------------- /2020-04-12-python-basics/loan_calculator.py: -------------------------------------------------------------------------------- 1 | name = "Cheuk" 2 | amount = 10_000 3 | interest_rate = 0.2 4 | year = 3 5 | 6 | payback = amount * (1+0.2) ** 3 7 | 8 | print(f"{name} has to pay back {payback}") 9 | -------------------------------------------------------------------------------- /2020-05-17-python-pytest/examples/code.py: -------------------------------------------------------------------------------- 1 | def serve_beer(age): 2 | if age is None: 3 | raise(ValueError("Tell me your age")) 4 | if age<18: 5 | return "No beer" 6 | else: 7 | return "Have beer" 8 | -------------------------------------------------------------------------------- /2020-08-03-python-docs/my_ops.py: -------------------------------------------------------------------------------- 1 | def my_func(x): 2 | """This is take the square of a number 3 | Parameters 4 | ---------- 5 | x : int, first variable 6 | Return 7 | ------ 8 | int, the squre of x 9 | """ 10 | return x*x -------------------------------------------------------------------------------- /2020-06-14-python-property-based-testing/test_demo.py: -------------------------------------------------------------------------------- 1 | from hypothesis import given, example 2 | from hypothesis.strategies import text 3 | from demo import * 4 | 5 | 6 | @given(text()) 7 | @example("") 8 | def test_decode_inverts_encode(s): 9 | assert decode(encode(s)) == s 10 | -------------------------------------------------------------------------------- /2020-04-19-python-basics-2/homework/exam_report.py: -------------------------------------------------------------------------------- 1 | mary = {'English' : 50, 'Math' : 100} 2 | david = {'English' : 95, 'Math' : 80} 3 | tom = {'English' : 60, 'Math' : 55} 4 | 5 | average_mark = # fill in the calculation 6 | 7 | # print out the report for each studnet 8 | 9 | # print average score for each subjects 10 | -------------------------------------------------------------------------------- /2020-05-10-python-classes/homework/one_number_bingo.py: -------------------------------------------------------------------------------- 1 | import random 2 | # to pick a random number: random.randint(1, 1000) 3 | 4 | wining_number = random.randint(1, 1000) 5 | total_spend = 0 6 | 7 | while True: 8 | pass #replace with your script 9 | 10 | 11 | # press control + c to stop infinite loop program 12 | -------------------------------------------------------------------------------- /2020-05-17-python-pytest/homework/one_number_bingo.py: -------------------------------------------------------------------------------- 1 | import random 2 | # to pick a random number: random.randint(1, 1000) 3 | 4 | wining_number = random.randint(1, 1000) 5 | total_spend = 0 6 | 7 | while True: 8 | pass #replace with your script 9 | 10 | 11 | # press control + c to stop infinite loop program 12 | -------------------------------------------------------------------------------- /2020-04-26-python-flow-control/homework/one_number_bingo.py: -------------------------------------------------------------------------------- 1 | import random 2 | # to pick a random number: random.randint(1, 1000) 3 | 4 | wining_number = random.randint(1, 1000) 5 | total_spend = 0 6 | 7 | while True: 8 | pass #replace with your script 9 | 10 | 11 | # press control + c to stop infinite loop program 12 | -------------------------------------------------------------------------------- /2020-05-03-python-functions/homework/one_number_bingo.py: -------------------------------------------------------------------------------- 1 | import random 2 | # to pick a random number: random.randint(1, 1000) 3 | 4 | wining_number = random.randint(1, 1000) 5 | total_spend = 0 6 | 7 | while True: 8 | pass #replace with your script 9 | 10 | 11 | # press control + c to stop infinite loop program 12 | -------------------------------------------------------------------------------- /2020-04-19-python-basics-2/examples/shopping_checkout.py: -------------------------------------------------------------------------------- 1 | catalog = {'apple': 1.5, 'banana': 0.8, 'toilet paper': 2} 2 | cheuk_shopping = ['banana'] + ['toilet paper']*2 3 | 4 | total = catalog[cheuk_shopping[0]] + catalog[cheuk_shopping[1]] + catalog[cheuk_shopping[2]] 5 | 6 | print(f"Cheuk is buying {cheuk_shopping}, and it's {total} pounds.") 7 | -------------------------------------------------------------------------------- /2020-04-19-python-basics-2/homework/combine_shopping.py: -------------------------------------------------------------------------------- 1 | tom_shopping = ['apple', 'toilet paper', 'magazines', 'banana'] 2 | matt_shopping = ['milk', 'banana', 'ice cream', 'toilet paper'] 3 | 4 | combine_list = # your code 5 | 6 | # print the count of each item 7 | 8 | # remove the redundant items 9 | 10 | # print the final combine list 11 | -------------------------------------------------------------------------------- /2020-06-14-python-property-based-testing/test_dateutil_parser.py: -------------------------------------------------------------------------------- 1 | from dateutil.parser import parse 2 | from hypothesis import given 3 | from hypothesis.strategies import text, datetimes 4 | 5 | 6 | @given(text(),datetimes(),text()) 7 | def test_parse(before,date_and_time,after): 8 | input = before + str(date_and_time) + after 9 | output = parse(input) 10 | assert output == date_and_time 11 | -------------------------------------------------------------------------------- /2020-06-28-python-tdd/eshopv2.py: -------------------------------------------------------------------------------- 1 | class Database: 2 | def __init__(self): 3 | self._all_baskets = [] 4 | 5 | def add_basket(self, bsk_id): 6 | self._all_baskets.append(bsk_id) 7 | 8 | class Basket: 9 | def __init__(self, user_name, db): 10 | self._name = user_name 11 | self._content = [] 12 | my_id = len(db._all_baskets) 13 | self._id = my_id 14 | db.add_basket(my_id) 15 | 16 | def add_item(self, item): 17 | self._content.append(item) 18 | -------------------------------------------------------------------------------- /2020-05-17-python-pytest/examples/test_code.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from .code import * 3 | 4 | class TestPub: 5 | 6 | def test_serve_beer_legal(self): 7 | adult = 25 8 | assert serve_beer(adult) == "Have beer" 9 | 10 | def test_serve_beer_illegal(self): 11 | child = 10 12 | assert serve_beer(child) == "No beer" 13 | 14 | def test_serve_beer_no_age(self): 15 | with pytest.raises(ValueError, match="Tell me your age"): 16 | age = None 17 | serve_beer(age) 18 | -------------------------------------------------------------------------------- /2020-05-24-python-decorators/examples/demo.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | def __init__(self): 3 | print("creating person") 4 | self.__name='unknow' 5 | @property 6 | def name(self): 7 | print("calling getter") 8 | return self.__name 9 | @name.setter 10 | def name(self, value): 11 | print("calling setter") 12 | self.__name=value 13 | @name.deleter 14 | def name(self): 15 | print('Deleting..') 16 | del self.__name 17 | 18 | me = Person() 19 | me.name = "Cheuk" 20 | del me.name 21 | -------------------------------------------------------------------------------- /2020-04-26-python-flow-control/examples/random_fruit.py: -------------------------------------------------------------------------------- 1 | import random 2 | basket = ["apple", "orange", "pear", "banana", "peach"] 3 | check_out = [] 4 | while True: #DANGER 5 | choice = random.choice(basket) 6 | if choice == "oranges": 7 | print(f"Oh no!") 8 | continue 9 | 10 | if choice == "banana": 11 | print("I have got banana!") 12 | check_out.append(choice) 13 | break 14 | else: 15 | print(f"I got {choice}. Try again") 16 | check_out.append(choice) 17 | 18 | print(f"At the end I got {check_out}") 19 | -------------------------------------------------------------------------------- /2020-05-10-python-classes/examples/demo.py: -------------------------------------------------------------------------------- 1 | class Basket: 2 | 3 | def __init__(self): 4 | self.content = [] 5 | self.add_multi_items = self.add_items 6 | 7 | def __add_item(self, item): 8 | self.content.append(item) 9 | print(f"{item} is added to basket.") 10 | 11 | def add_items(self, *args): 12 | """This method add items to the content""" 13 | for item in args: 14 | self.__add_item(item) 15 | 16 | my_basket = Basket() 17 | 18 | my_basket.__add_item("toilet papers") 19 | print("My basket: ", my_basket.content) 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Zero to Hero 2 | 3 | Pyton Zero to Hero is a tutorial series for Python Absolute beginners. I will teach all I know to help people being able to use Python for their personal projects, open-source projects or even for work, starting form installing Python to . 4 | 5 | Tutorials will be streaming live on [Twitch](https://www.twitch.tv/cheukting_ho) every Sunday 1pm (UK time). Previous recordings will be available on [my website](https://cheuk.dev/#videos) or [YouTube](https://www.youtube.com/playlist?list=PLuyh0gfVhNpEd2m3XQq8hczlsUXN36Odc). 6 | 7 | This is the example codes I wrote every week. 8 | -------------------------------------------------------------------------------- /2020-04-19-python-basics-2/examples/family_checker.py: -------------------------------------------------------------------------------- 1 | john = {'father' : 'David', 'mother' : 'May'} 2 | lucy = {'father' : 'Geoge', 'mother' : 'Teresa'} 3 | mary = {'father' : john, 'mother' : lucy} 4 | 5 | grand_parents_of_mary = [mary['father']['father']] 6 | grand_parents_of_mary.append(mary['mother']['father']) 7 | grand_parents_of_mary.append(mary['father']['mother']) 8 | grand_parents_of_mary.append(mary['mother']['mother']) 9 | 10 | this_person = 'David' 11 | that_person = 'Tom' 12 | 13 | print(f"{this_person} is Mary's granny? {this_person in grand_parents_of_mary}") 14 | print(f"{that_person} is Mary's granny? {that_person in grand_parents_of_mary}") 15 | -------------------------------------------------------------------------------- /2020-06-14-python-property-based-testing/demo.py: -------------------------------------------------------------------------------- 1 | def encode(input_string): 2 | if not input_string: 3 | return [] 4 | count = 1 5 | prev = "" 6 | lst = [] 7 | for character in input_string: 8 | if character != prev: 9 | if prev: 10 | entry = (prev, count) 11 | lst.append(entry) 12 | count = 1 13 | prev = character 14 | else: 15 | count += 1 16 | entry = (character, count) 17 | lst.append(entry) 18 | return lst 19 | 20 | 21 | def decode(lst): 22 | q = "" 23 | for character, count in lst: 24 | q += character * count 25 | return q 26 | -------------------------------------------------------------------------------- /2020-05-24-python-decorators/examples/greeting_w_jokes.py: -------------------------------------------------------------------------------- 1 | 2 | from functools import wraps 3 | 4 | def adding_jokes(greeting): 5 | @wraps(greeting) 6 | def better_greeting(*args, **kwargs): 7 | """This is a function that greets and tell a joke""" 8 | greeting(*args, **kwargs) 9 | print("How did the farmer find his missing cow? He tractor down") 10 | return better_greeting 11 | 12 | @adding_jokes 13 | def greeting(name): 14 | "This is a simple greeting" 15 | print(f"Hello, {name}") 16 | 17 | @adding_jokes 18 | def special_greeting(name, gender): 19 | if gender == "female": 20 | print(f"hey babe, {name}") 21 | else: 22 | print(f"sup bro, {name}") 23 | 24 | special_greeting("Cheuk", "female") 25 | -------------------------------------------------------------------------------- /2020-04-26-python-flow-control/examples/combine_checkout.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | tom_shopping = ['apple', 'toilet paper', 'magazine', 'banana'] 4 | matt_shopping = ['milk', 'banana', 'ice cream', 'toilet paper'] 5 | 6 | catalog = {'apple': 1.5, 7 | 'toilet paper': 5, 8 | 'magazine': 10, 9 | 'milk': 0.5, 10 | 'banana': 0.4, 11 | 'ice cream': 3} 12 | 13 | combine_list = copy.copy(tom_shopping) 14 | 15 | for item in matt_shopping: 16 | if item not in tom_shopping: 17 | combine_list.append(item) 18 | 19 | print(f"The cobined list is {combine_list}") 20 | 21 | total_amount = 0 22 | 23 | for item in combine_list: 24 | total_amount += catalog[item] 25 | 26 | print(f"They spend £{total_amount} in total.") 27 | -------------------------------------------------------------------------------- /2020-05-10-python-classes/examples/e-shop.py: -------------------------------------------------------------------------------- 1 | class Basket: 2 | 3 | def __init__(self, database, name, address): 4 | self.id = len(database.keys())+1 5 | self.name = name 6 | self.address = address 7 | self.content = [] 8 | self.add_multi_items = self.add_items 9 | database[self.id] = self 10 | 11 | def _add_item(self, item): 12 | self.content.append(item) 13 | print(f"{item} is added to basket.") 14 | 15 | def add_items(self, *args): 16 | """This method add items to the content""" 17 | for item in args: 18 | self._add_item(item) 19 | 20 | database = {} 21 | 22 | my_basket = Basket(database, "Cheuk", "123 Williton Street, London, UK") 23 | my_basket.add_items("toilet papers") 24 | print("My basket: ", my_basket.content) 25 | 26 | print(database[1].name) 27 | -------------------------------------------------------------------------------- /2020-05-17-python-pytest/examples/e_shop.py: -------------------------------------------------------------------------------- 1 | class Basket: 2 | 3 | def __init__(self, database, name, address): 4 | self.id = len(database.keys())+1 5 | self.name = name 6 | self.address = address 7 | self.content = [] 8 | self.add_multi_items = self.add_items 9 | database[self.id] = self 10 | 11 | def _add_item(self, item): 12 | self.content.append(item) 13 | print(f"{item} is added to basket.") 14 | 15 | def add_items(self, *args): 16 | """This method add items to the content""" 17 | for item in args: 18 | self._add_item(item) 19 | 20 | database = {} 21 | 22 | my_basket = Basket(database, "Cheuk", "123 Williton Street, London, UK") 23 | my_basket.add_items("toilet papers") 24 | print("My basket: ", my_basket.content) 25 | 26 | print(database[1].name) 27 | -------------------------------------------------------------------------------- /2020-05-03-python-functions/examples/checkout_sum.py: -------------------------------------------------------------------------------- 1 | shop_catalog = {'toilet paper': 10, 2 | 'banana': 0.8, 3 | 'coffee beans': 3} 4 | 5 | def checkout(shop_list, catalog=shop_catalog): 6 | """This function calculate how much a customer need to pay. 7 | 8 | Parameters 9 | ========== 10 | shop_list, list 11 | catalog, dict 12 | 13 | Returs 14 | ====== 15 | checkout_sum, float""" 16 | checkout_sum = sum([catalog[item] for item in shop_list]) 17 | print(f"Thank you, the total is £{checkout_sum}") 18 | return checkout_sum 19 | 20 | my_shop_list = ['toilet paper', 'banana'] 21 | to_pay = checkout(my_shop_list) 22 | print(f"I have to pay {to_pay}") 23 | 24 | your_shop_list = ['banana', 'coffee beans'] 25 | you_have_to_pay = checkout(your_shop_list, shop_catalog) 26 | print(f"You have to pay {you_have_to_pay}") 27 | -------------------------------------------------------------------------------- /2020-05-03-python-functions/examples/random_fruit.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def lucky_draw(basket): 4 | check_out = [] 5 | while True: #DANGER 6 | choice = random.choice(basket) 7 | if choice == "oranges": 8 | print(f"Oh no!") 9 | continue 10 | if choice == "banana": 11 | print("I have got banana!") 12 | check_out.append(choice) 13 | break 14 | else: 15 | print(f"I got {choice}. Try again") 16 | check_out.append(choice) 17 | return check_out 18 | 19 | my_basket = ["apple", "orange", "pear", "banana", "peach"] 20 | print(f"At the end I got {lucky_draw(my_basket)}") 21 | 22 | print("Another basket") 23 | another_basket = ["apple", "orange", "pear", "banana", "peach", "apple", "apple", "apple", "apple"] 24 | print(f"At the end I got {lucky_draw(another_basket)}") 25 | -------------------------------------------------------------------------------- /2020-05-03-python-functions/examples/combine_checkout.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import checkout_sum as cs 3 | 4 | def combine_the_list(list1, list2): 5 | combine_list = copy.copy(list1) 6 | 7 | for item in list2: 8 | if item not in list1: 9 | combine_list.append(item) 10 | 11 | return combine_list 12 | 13 | tom_shopping = ['apple', 'toilet paper', 'magazine', 'banana'] 14 | matt_shopping = ['milk', 'banana', 'ice cream', 'toilet paper'] 15 | 16 | catalog = {'apple': 1.5, 17 | 'toilet paper': 5, 18 | 'magazine': 10, 19 | 'milk': 0.5, 20 | 'banana': 0.4, 21 | 'ice cream': 3} 22 | 23 | combine_list = combine_the_list(tom_shopping, matt_shopping) 24 | 25 | print(f"The cobined list is {combine_list}") 26 | 27 | total_amount = cs.checkout(combine_list, catalog) 28 | 29 | print(f"They spend £{total_amount} in total.") 30 | -------------------------------------------------------------------------------- /2020-05-17-python-pytest/examples/test_e_shop.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from .e_shop import Basket 3 | 4 | database = {} 5 | 6 | class TestBasket: 7 | 8 | def test_create_basket(self): 9 | my_basket = Basket(database, "Cheuk", "123 Williton Street") 10 | 11 | assert my_basket.id == 1 12 | assert my_basket.name == "Cheuk" 13 | assert my_basket.address == "123 Williton Street" 14 | assert my_basket.content == [] 15 | 16 | def test_add_item(self): 17 | my_basket = Basket(database, "Cheuk", "123 Williton Street") 18 | my_basket._add_item("apple") 19 | assert my_basket.content == ["apple"] 20 | 21 | def test_add_items(self): 22 | my_basket = Basket(database, "Cheuk", "123 Williton Street") 23 | item_list = ['apple', 'orange'] 24 | my_basket.add_items(*item_list) 25 | assert my_basket.content == item_list 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Cheuk Ting Ho 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /2020-06-28-python-tdd/test_eshopv2.py: -------------------------------------------------------------------------------- 1 | from hypothesis import given 2 | from hypothesis.strategies import integers, text 3 | from eshopv2 import Basket, Database 4 | 5 | class TestBasket: 6 | def test_init_basket(self): 7 | my_db = Database() 8 | user_name = "cheuk" 9 | content = [] 10 | my_basket = Basket(user_name, my_db) 11 | assert my_basket._name == user_name 12 | assert my_basket._content == [] 13 | assert my_basket._id == 0 14 | 15 | def test_2_baskets(self): 16 | my_db = Database() 17 | basket1 = Basket("cheuk", my_db) 18 | basket2 = Basket("amy", my_db) 19 | assert basket1._id == 0 20 | assert basket2._id == 1 21 | 22 | @given(text()) 23 | def test_add_item_to_bsk(self, item): 24 | my_db = Database() 25 | user_name = "cheuk" 26 | my_basket = Basket(user_name, my_db) 27 | my_basket.add_item(item) 28 | assert my_basket._content == [item] 29 | 30 | class TestDatabase: 31 | def test_init_database(self): 32 | my_db = Database() 33 | assert my_db._all_baskets == [] 34 | 35 | @given(integers(0,999)) 36 | def test_add_basket(self, bsk_id): 37 | my_db = Database() 38 | my_db.add_basket(bsk_id) 39 | assert my_db._all_baskets == [bsk_id] 40 | -------------------------------------------------------------------------------- /2020-05-24-python-decorators/examples/e-shop.py: -------------------------------------------------------------------------------- 1 | class Basket: 2 | 3 | def __init__(self, database, name, address): 4 | self.__id = len(database.keys())+1 5 | self.__name = name 6 | self.__address = address 7 | self.__content = [] 8 | self.add_multi_items = self.add_items 9 | database[self.__id] = self 10 | 11 | @property 12 | def id(self): 13 | return self.__id 14 | 15 | @property 16 | def name(self): 17 | return self.__name 18 | 19 | @name.setter 20 | def name(self, input): 21 | if type(input) != str: 22 | raise ValueError("Name need to be a string") 23 | self.__name = input 24 | 25 | @property 26 | def address(self): 27 | return self.__address 28 | 29 | @address.setter 30 | def address(self, input): 31 | if type(input) != str: 32 | raise ValueError("Address need to be a string") 33 | self.__address = input 34 | 35 | @property 36 | def content(self): 37 | print("In the basket there are:") 38 | for item in self.__content: 39 | print(item) 40 | return self.__content 41 | 42 | @content.setter 43 | def content(self, input): 44 | if type(input) != list: 45 | raise ValueError("Content need to be a list") 46 | self.__content = input 47 | 48 | def _add_item(self, item): 49 | self.__content.append(item) 50 | print(f"{item} is added to basket.") 51 | 52 | def add_items(self, *args): 53 | """This method add items to the content""" 54 | for item in args: 55 | self._add_item(item) 56 | 57 | database = {} 58 | 59 | my_basket = Basket(database, "Cheuk", "123 Williton Street, London, UK") 60 | my_basket.add_items("toilet papers") 61 | my_basket.content = ["coffee beans", "toiler papers"] 62 | the_content = my_basket.content 63 | print("My basket: ", my_basket.content) 64 | 65 | #print(database[1].address) 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /2020-05-31-python-strings-regex/examples/e-shop.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | class Basket: 4 | 5 | def __init__(self, database, name, address, email): 6 | self.__id = len(database.keys())+1 7 | self.__name = name 8 | self.__address = address 9 | self.email = email 10 | #self.__email = email 11 | self.__content = [] 12 | self.add_multi_items = self.add_items 13 | database[self.__id] = self 14 | 15 | @property 16 | def id(self): 17 | return self.__id 18 | 19 | @property 20 | def name(self): 21 | return self.__name 22 | 23 | @name.setter 24 | def name(self, input): 25 | if type(input) != str: 26 | raise ValueError("Name need to be a string") 27 | self.__name = input 28 | 29 | @property 30 | def address(self): 31 | return self.__address 32 | 33 | @address.setter 34 | def address(self, input): 35 | if type(input) != str: 36 | raise ValueError("Address need to be a string") 37 | self.__address = input 38 | 39 | @property 40 | def email(self): 41 | return self.__email 42 | 43 | @address.setter 44 | def email(self, input): 45 | if type(input) != str: 46 | raise ValueError("Email adress need to be a string") 47 | match = re.match("^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$", input) 48 | if not match: 49 | raise ValueError("Not a valid emial address") 50 | self.__email = input 51 | 52 | @property 53 | def content(self): 54 | print("In the basket there are:") 55 | for item in self.__content: 56 | print(item) 57 | return self.__content 58 | 59 | @content.setter 60 | def content(self, input): 61 | if type(input) != list: 62 | raise ValueError("Content need to be a list") 63 | self.__content = input 64 | 65 | def _add_item(self, item): 66 | self.__content.append(item) 67 | print(f"{item} is added to basket.") 68 | 69 | def add_items(self, *args): 70 | """This method add items to the content""" 71 | for item in args: 72 | self._add_item(item) 73 | 74 | database = {} 75 | 76 | my_basket = Basket(database, "Cheuk", "123 Williton Street, London, UK", "my_email@gmail.com") 77 | my_basket.add_items("toilet papers") 78 | my_basket.content = ["coffee beans", "toiler papers"] 79 | the_content = my_basket.content 80 | print("My basket: ", my_basket.content) 81 | 82 | #print(database[1].address) 83 | -------------------------------------------------------------------------------- /2020-06-21-python-linting/examples/e-shop.py: -------------------------------------------------------------------------------- 1 | import pytest # isort:skip 2 | import math 3 | import re 4 | 5 | 6 | class Basket: 7 | def __init__(self, database, name, address, email): 8 | self.__id = len(database.keys()) + 1 9 | self.__name = name 10 | self.__address = address 11 | self.email = email 12 | # self.__email = email 13 | self.__content = [] 14 | self.add_multi_items = self.add_items 15 | database[self.__id] = self 16 | 17 | @property 18 | def id(self): 19 | return self.__id 20 | 21 | @property 22 | def name(self): 23 | return self.__name 24 | 25 | @name.setter 26 | def name(self, input): 27 | if type(input) != str: 28 | raise ValueError("Name need to be a string") 29 | self.__name = input 30 | 31 | @property 32 | def address(self): 33 | return self.__address 34 | 35 | @address.setter 36 | def address(self, input): 37 | if type(input) != str: 38 | raise ValueError("Address need to be a string") 39 | self.__address = input 40 | 41 | @property 42 | def email(self): 43 | return self.__email 44 | 45 | @address.setter 46 | def email(self, input): 47 | if type(input) != str: 48 | raise ValueError("Email adress need to be a string") 49 | match = re.match("^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$", input) 50 | if not match: 51 | raise ValueError("Not a valid emial address") 52 | self.__email = input 53 | 54 | @property 55 | def content(self): 56 | print("In the basket there are:") 57 | for item in self.__content: 58 | print(item) 59 | return self.__content 60 | 61 | @content.setter 62 | def content(self, input): 63 | if type(input) != list: 64 | raise ValueError("Content need to be a list") 65 | self.__content = input 66 | 67 | def _add_item(self, item): 68 | self.__content.append(item) 69 | print(f"{item} is added to basket.") 70 | 71 | def add_items(self, *args): 72 | """This method add items to the content""" 73 | for item in args: 74 | self._add_item(item) 75 | 76 | 77 | database = {} 78 | # fmt:off 79 | my_basket = Basket(database, "Cheuk", "123 Williton Street, London, UK", "my_email@gmail.com") 80 | # fmt:on 81 | my_basket.add_items("toilet papers") 82 | my_basket.content = ["coffee beans", "toiler papers"] 83 | the_content = my_basket.content 84 | print("My basket: ", my_basket.content) 85 | # print(database[1].address) 86 | -------------------------------------------------------------------------------- /2020-08-03-python-docs/using_my_ops.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from my_ops import my_func" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "my_func" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "?my_func" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "my_func(2)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "from os import path " 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "?path" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "metadata": {}, 61 | "outputs": [], 62 | "source": [ 63 | "from math import pi" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "?pi" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "from math import sin" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": null, 87 | "metadata": {}, 88 | "outputs": [], 89 | "source": [ 90 | "?sin" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": null, 96 | "metadata": {}, 97 | "outputs": [], 98 | "source": [ 99 | "sin(3.14)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": null, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "sin.__doc__" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": null, 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [] 117 | } 118 | ], 119 | "metadata": { 120 | "kernelspec": { 121 | "display_name": "Python 3", 122 | "language": "python", 123 | "name": "python3" 124 | }, 125 | "language_info": { 126 | "codemirror_mode": { 127 | "name": "ipython", 128 | "version": 3 129 | }, 130 | "file_extension": ".py", 131 | "mimetype": "text/x-python", 132 | "name": "python", 133 | "nbconvert_exporter": "python", 134 | "pygments_lexer": "ipython3", 135 | "version": "3.7.3" 136 | } 137 | }, 138 | "nbformat": 4, 139 | "nbformat_minor": 4 140 | } 141 | -------------------------------------------------------------------------------- /2020-07-26-python-async/async.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Generators" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "def numberGenerator(n):\n", 17 | " number = yield\n", 18 | " while number < n:\n", 19 | " number = yield number \n", 20 | " number += 1\n", 21 | "\n", 22 | "g = numberGenerator(10) # Create our generator\n", 23 | "next(g) # \n", 24 | "print(g.send(5))" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "next(g.send(10))" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "def bottom():\n", 43 | " # Returning the yield lets the value\n", 44 | " # that goes up the call stack\n", 45 | " # to come right back down.\n", 46 | " return (yield 42)\n", 47 | "\n", 48 | "def middle():\n", 49 | " return (yield from bottom())\n", 50 | "\n", 51 | "def top():\n", 52 | " return (yield from middle())\n", 53 | "\n", 54 | "# Get the generator.\n", 55 | "gen = top()\n", 56 | "value = next(gen)\n", 57 | "print(value) # Prints '42'.\n", 58 | "try:\n", 59 | " value = gen.send(value * 2)\n", 60 | "except StopIteration as exc:\n", 61 | " value = exc.value\n", 62 | "print(value) # Prints '84'." 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "# async.io" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "import asyncio\n", 79 | "\n", 80 | "# Borrowed from http://curio.readthedocs.org/en/latest/tutorial.html.\n", 81 | "@asyncio.coroutine\n", 82 | "def countdown(number, n):\n", 83 | " while n > 0:\n", 84 | " print('T-minus', n, '({})'.format(number))\n", 85 | " yield from asyncio.sleep(1)\n", 86 | " n -= 1\n", 87 | "\n", 88 | "loop = asyncio.get_event_loop()\n", 89 | "tasks = [\n", 90 | " asyncio.ensure_future(countdown(\"A\", 2)),\n", 91 | " asyncio.ensure_future(countdown(\"B\", 3))]\n", 92 | "loop.run_until_complete(asyncio.wait(tasks))\n", 93 | "loop.close()" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "# Not using async" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": null, 106 | "metadata": {}, 107 | "outputs": [], 108 | "source": [ 109 | "import time\n", 110 | "# Borrowed from http://curio.readthedocs.org/en/latest/tutorial.html.\n", 111 | "def countdown(number, n):\n", 112 | " while n > 0:\n", 113 | " print('T-minus', n, '({})'.format(number))\n", 114 | " yield time.sleep(1)\n", 115 | " n -= 1\n", 116 | "\n", 117 | "for item in countdown(\"A\", 2):\n", 118 | " continue\n", 119 | "for item in countdown(\"B\", 3):\n", 120 | " continue" 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": {}, 126 | "source": [ 127 | "# Async / await" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "async def countdown(number, n):\n", 137 | " while n > 0:\n", 138 | " print('T-minus', n, '({})'.format(number))\n", 139 | " await asyncio.sleep(1)\n", 140 | " n -= 1\n", 141 | "loop = asyncio.get_event_loop()\n", 142 | "tasks = [\n", 143 | " asyncio.ensure_future(countdown(\"A\", 2)),\n", 144 | " asyncio.ensure_future(countdown(\"B\", 3))]\n", 145 | "loop.run_until_complete(asyncio.wait(tasks))\n", 146 | "loop.close()" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": null, 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [] 155 | } 156 | ], 157 | "metadata": { 158 | "kernelspec": { 159 | "display_name": "Python 3", 160 | "language": "python", 161 | "name": "python3" 162 | }, 163 | "language_info": { 164 | "codemirror_mode": { 165 | "name": "ipython", 166 | "version": 3 167 | }, 168 | "file_extension": ".py", 169 | "mimetype": "text/x-python", 170 | "name": "python", 171 | "nbconvert_exporter": "python", 172 | "pygments_lexer": "ipython3", 173 | "version": "3.7.3" 174 | } 175 | }, 176 | "nbformat": 4, 177 | "nbformat_minor": 4 178 | } 179 | -------------------------------------------------------------------------------- /2020-07-19-python-generators/generators.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Try creating a generator" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "def firstn(n):\n", 17 | " num = 0\n", 18 | " print(\"we are ready!\")\n", 19 | " while num < n:\n", 20 | " yield num\n", 21 | " num += 1\n", 22 | " print(f\"It's done, num={num}\")\n", 23 | " return None\n", 24 | " print(\"After return\")" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "my_obj = firstn(3)" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "for item in my_obj:\n", 43 | " print(f\"--- iter{item} ---\")\n", 44 | " print(item)" 45 | ] 46 | }, 47 | { 48 | "cell_type": "markdown", 49 | "metadata": {}, 50 | "source": [ 51 | "# Inspect what's in a generator" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "gen_obj = firstn(10)" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "dir(gen_obj)" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "gen_obj" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "iter(gen_obj)" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "def my_func(n):\n", 97 | " n = n + 1\n", 98 | " return n" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "dir(my_func)" 108 | ] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "metadata": {}, 113 | "source": [ 114 | "# Play with generator" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "another_obj = firstn(3)" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": null, 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [ 132 | "item = next(another_obj)" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "print(item)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "item2 = next(another_obj)" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "print(item2)" 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "# Sending to generator" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "metadata": {}, 173 | "outputs": [], 174 | "source": [ 175 | "def numberGenerator(n):\n", 176 | " number = yield\n", 177 | " print(\"Inside gen: \",number)\n", 178 | " while number < n:\n", 179 | " print(\"going to yield: \", number)\n", 180 | " number = yield number \n", 181 | " print(\"getting number: \", number)\n", 182 | " number += 1\n", 183 | "\n", 184 | "g = numberGenerator(10) # Create our generator\n", 185 | "next(g) # \n", 186 | "print(g.send(5))" 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": null, 192 | "metadata": {}, 193 | "outputs": [], 194 | "source": [ 195 | "print(g.send(2))" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "print(g.send(5))" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": null, 210 | "metadata": {}, 211 | "outputs": [], 212 | "source": [ 213 | "def my_func(n):\n", 214 | " return n" 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": {}, 220 | "source": [ 221 | "# Yield from" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | "def big_gen(n):\n", 231 | " print(\"Inside big_gen\")\n", 232 | " yield from firstn(n)\n", 233 | " print(\"End of big_gen\")\n", 234 | " " 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": null, 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "dir(big_gen(10))" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": null, 249 | "metadata": {}, 250 | "outputs": [], 251 | "source": [ 252 | "big_gen(10)" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": null, 258 | "metadata": {}, 259 | "outputs": [], 260 | "source": [ 261 | "for item in big_gen(10):\n", 262 | " print(item)" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": null, 268 | "metadata": {}, 269 | "outputs": [], 270 | "source": [] 271 | } 272 | ], 273 | "metadata": { 274 | "kernelspec": { 275 | "display_name": "Python 3", 276 | "language": "python", 277 | "name": "python3" 278 | }, 279 | "language_info": { 280 | "codemirror_mode": { 281 | "name": "ipython", 282 | "version": 3 283 | }, 284 | "file_extension": ".py", 285 | "mimetype": "text/x-python", 286 | "name": "python", 287 | "nbconvert_exporter": "python", 288 | "pygments_lexer": "ipython3", 289 | "version": "3.7.3" 290 | } 291 | }, 292 | "nbformat": 4, 293 | "nbformat_minor": 4 294 | } 295 | -------------------------------------------------------------------------------- /2020-08-23-python-functional.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", 10 | "result = 0\n", 11 | "for num in num_list:\n", 12 | " if num % 2 == 0:\n", 13 | " result += num * 10\n", 14 | "print(result)" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "from functools import reduce\n", 24 | "print(reduce(lambda x,y: x+y,\n", 25 | " map(lambda a: a*10,\n", 26 | " filter(lambda n: n%2==0,\n", 27 | " [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))))" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "# Lambda Function" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "def my_func(n):\n", 44 | " return n**2" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "my_func(10)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": null, 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "my_lambda_func = lambda n: n**2" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "metadata": {}, 69 | "outputs": [], 70 | "source": [ 71 | "my_lambda_func(10)" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "# Map\n", 86 | "https://docs.python.org/3/library/functions.html#map" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "mapper = map(lambda n: n**2, [1,2,3])" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "list(mapper)" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "metadata": {}, 111 | "outputs": [], 112 | "source": [ 113 | "list(map(lambda n: n**2, [1,2,3]))" 114 | ] 115 | }, 116 | { 117 | "cell_type": "markdown", 118 | "metadata": {}, 119 | "source": [ 120 | "# Filter\n", 121 | "https://docs.python.org/3/library/functions.html#filter" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "metadata": {}, 128 | "outputs": [], 129 | "source": [ 130 | "my_list = [12,54,-545,-837,234,675]" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": null, 136 | "metadata": {}, 137 | "outputs": [], 138 | "source": [ 139 | "filtered = list(filter(lambda x: x >= 0, my_list))" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "filtered" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": null, 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [ 157 | "list(map(lambda x: x-10, filter(lambda x: x >= 0, my_list)))" 158 | ] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "metadata": {}, 163 | "source": [ 164 | "# functools.reduce\n", 165 | "https://docs.python.org/3/library/functools.html" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": null, 171 | "metadata": {}, 172 | "outputs": [], 173 | "source": [ 174 | "from functools import reduce\n", 175 | "reduce(lambda x,y: x+y, my_list)" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": null, 181 | "metadata": {}, 182 | "outputs": [], 183 | "source": [ 184 | "sum(my_list)" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "reduce(lambda x,y: str(x) + ',' + str(y), filtered)" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": null, 199 | "metadata": {}, 200 | "outputs": [], 201 | "source": [] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "metadata": {}, 206 | "source": [ 207 | "# Put them together" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "reduce(lambda x,y: str(x) + ',' + str(y), map(lambda x: x-10, filter(lambda x: x >= 0, my_list)))" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": null, 222 | "metadata": {}, 223 | "outputs": [], 224 | "source": [] 225 | }, 226 | { 227 | "cell_type": "markdown", 228 | "metadata": {}, 229 | "source": [ 230 | "# List comprehenstion" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": null, 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "[i**2 for i in [1,2,3]]" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": null, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "new_list=[]\n", 249 | "for i in [1,2,3]:\n", 250 | " new_list.append(i**2)\n", 251 | "new_list" 252 | ] 253 | }, 254 | { 255 | "cell_type": "markdown", 256 | "metadata": {}, 257 | "source": [ 258 | "# Sortting a list" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": null, 264 | "metadata": {}, 265 | "outputs": [], 266 | "source": [ 267 | "sorted(iterable, *, key=None, reverse=False)" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": null, 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "sorted([2453,28,134])" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "sorted(['2453','28','134'])" 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": null, 291 | "metadata": {}, 292 | "outputs": [], 293 | "source": [ 294 | "sorted([2453,28,134], key = lambda x: str(x))" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": null, 300 | "metadata": {}, 301 | "outputs": [], 302 | "source": [] 303 | } 304 | ], 305 | "metadata": { 306 | "kernelspec": { 307 | "display_name": "Python 3", 308 | "language": "python", 309 | "name": "python3" 310 | }, 311 | "language_info": { 312 | "codemirror_mode": { 313 | "name": "ipython", 314 | "version": 3 315 | }, 316 | "file_extension": ".py", 317 | "mimetype": "text/x-python", 318 | "name": "python", 319 | "nbconvert_exporter": "python", 320 | "pygments_lexer": "ipython3", 321 | "version": "3.7.3" 322 | } 323 | }, 324 | "nbformat": 4, 325 | "nbformat_minor": 4 326 | } 327 | -------------------------------------------------------------------------------- /2020-09-06-python-os-subprocess.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Read and Write file" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "!echo \"Hello! Welcome to demofile.txt\\nThis file is for testing purposes.\\nGood Luck!\\n\" >> demofile.txt" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "f = open(\"demofile.txt\", \"r\")\n", 26 | "print(f.read())" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "f.close()" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": null, 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "f = open(\"demofile.txt\", \"r\")\n", 45 | "print(f.read(5))" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "f.close()" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "metadata": {}, 61 | "outputs": [], 62 | "source": [ 63 | "f = open(\"demofile.txt\", \"r\")\n", 64 | "print(f.readline())" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "print(f.readline())" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "f.close()" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "f = open(\"demofile.txt\", \"r\")" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [ 100 | "my_readline = f.__iter__()" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": null, 106 | "metadata": {}, 107 | "outputs": [], 108 | "source": [ 109 | "next(my_readline)" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "f.readline()" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "id(f.readline())" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "id(my_readline)" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "dir(f.readline())" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": {}, 152 | "outputs": [], 153 | "source": [ 154 | "f = open(\"demofile.txt\", \"r\")\n", 155 | "for line in f:\n", 156 | " print(line)\n", 157 | " print(\"-------\")" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "f.close()" 167 | ] 168 | }, 169 | { 170 | "cell_type": "markdown", 171 | "metadata": {}, 172 | "source": [ 173 | "# Writing a file" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [ 182 | "f = open(\"demofile.txt\", \"a\")\n", 183 | "f.write(\"Now the file has more content!\\n\")\n", 184 | "f.close()\n", 185 | "\n", 186 | "#open and read the file after the appending:\n", 187 | "f = open(\"demofile.txt\", \"r\")\n", 188 | "print(f.read())" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "f = open(\"demofile.txt\", \"w\")\n", 198 | "f.write(\"Woops! I have deleted the content!\")\n", 199 | "f.close()\n", 200 | "\n", 201 | "#open and read the file after the appending:\n", 202 | "f = open(\"demofile.txt\", \"r\")\n", 203 | "print(f.read())" 204 | ] 205 | }, 206 | { 207 | "cell_type": "markdown", 208 | "metadata": {}, 209 | "source": [ 210 | "# os" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "import os\n", 220 | "os.getcwd()" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "os.listdir(os.getcwd())" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "os.path.abspath(\"./\")" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": null, 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "os.path.abspath(\"demotext.txt\")" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "metadata": {}, 254 | "outputs": [], 255 | "source": [ 256 | "os.path.dirname(os.path.abspath(\"./demotext.txt\"))" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": null, 262 | "metadata": {}, 263 | "outputs": [], 264 | "source": [ 265 | "os.path.join(os.getcwd(),\"demotext.txt\")" 266 | ] 267 | }, 268 | { 269 | "cell_type": "markdown", 270 | "metadata": {}, 271 | "source": [ 272 | "# subprocess" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": null, 278 | "metadata": {}, 279 | "outputs": [], 280 | "source": [ 281 | "!ls" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "metadata": {}, 288 | "outputs": [], 289 | "source": [ 290 | "import subprocess" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": null, 296 | "metadata": {}, 297 | "outputs": [], 298 | "source": [ 299 | "my_process = subprocess.run(\"ls\", capture_output=True)" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": null, 305 | "metadata": {}, 306 | "outputs": [], 307 | "source": [ 308 | "my_process.stdout" 309 | ] 310 | }, 311 | { 312 | "cell_type": "code", 313 | "execution_count": null, 314 | "metadata": {}, 315 | "outputs": [], 316 | "source": [ 317 | "!ls -a" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "metadata": {}, 324 | "outputs": [], 325 | "source": [ 326 | "my_process = subprocess.run([\"ls\", \"-a\"], capture_output=True)" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": null, 332 | "metadata": {}, 333 | "outputs": [], 334 | "source": [ 335 | "my_process.stdout" 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "metadata": {}, 342 | "outputs": [], 343 | "source": [] 344 | } 345 | ], 346 | "metadata": { 347 | "kernelspec": { 348 | "display_name": "Python 3", 349 | "language": "python", 350 | "name": "python3" 351 | }, 352 | "language_info": { 353 | "codemirror_mode": { 354 | "name": "ipython", 355 | "version": 3 356 | }, 357 | "file_extension": ".py", 358 | "mimetype": "text/x-python", 359 | "name": "python", 360 | "nbconvert_exporter": "python", 361 | "pygments_lexer": "ipython3", 362 | "version": "3.7.3" 363 | } 364 | }, 365 | "nbformat": 4, 366 | "nbformat_minor": 4 367 | } 368 | -------------------------------------------------------------------------------- /2020-08-30-more-python-list-dict.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Look at list" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "my_list = [1,2,3]" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "dir(my_list)" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "my_list.__getitem__(1)" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "my_list[1]" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "dir(my_list.__iter__())" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "my_list_iter = iter(my_list)" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "my_list_iter.__next__()" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "next(my_list_iter)" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [ 88 | "my_list == [2,1,3]" 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "# List comprehension" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "h_letters = []\n", 105 | " \n", 106 | "for letter in 'human':\n", 107 | " h_letters.append(letter)\n", 108 | "\n", 109 | "print(h_letters)" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "h_letters = [ letter.upper() for letter in 'human' ]\n", 119 | "print(h_letters)" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": {}, 126 | "outputs": [], 127 | "source": [ 128 | "list(map(lambda n: n**2, my_list))" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": {}, 135 | "outputs": [], 136 | "source": [ 137 | "[ n**2 for n in my_list ]" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "my_list2 = [12,54,-545,-837,234,675]\n", 147 | "list(filter(lambda x: x >= 0, my_list2))" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "metadata": {}, 154 | "outputs": [], 155 | "source": [ 156 | "[ x for x in my_list2 if x>=0 ]" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "[ \"+\" if x >=0 else \"-\" for x in my_list2]" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": null, 171 | "metadata": {}, 172 | "outputs": [], 173 | "source": [ 174 | "for x in my_list2:\n", 175 | " print(\"+\" if x >=0 else \"-\")" 176 | ] 177 | }, 178 | { 179 | "cell_type": "markdown", 180 | "metadata": {}, 181 | "source": [ 182 | "# Sorted" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": null, 188 | "metadata": {}, 189 | "outputs": [], 190 | "source": [ 191 | "my_dict = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}" 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": null, 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "for x in range(3,0,-1):\n", 201 | " print(x)" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "sorted(range(3,0,-1))" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "\"This is a test string from Andrew\".split()" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": null, 225 | "metadata": {}, 226 | "outputs": [], 227 | "source": [ 228 | "sorted(\"This is a test string from Andrew\".split(), key=lambda x: len(x))" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": null, 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [ 237 | "student_tuples = [\n", 238 | " ('john', 'A', 15),\n", 239 | " ('jane', 'B', 18),\n", 240 | " ('dave', 'B', 10),\n", 241 | "]\n", 242 | "sorted(student_tuples, key=lambda student: student[2])" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": null, 248 | "metadata": {}, 249 | "outputs": [], 250 | "source": [ 251 | "class Student:\n", 252 | " def __init__(self, name, grade, age):\n", 253 | " self.name = name\n", 254 | " self.grade = grade\n", 255 | " self.age = age\n", 256 | " def __repr__(self):\n", 257 | " return repr((self.name, self.grade, self.age))" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "metadata": {}, 264 | "outputs": [], 265 | "source": [ 266 | "student_objects = [\n", 267 | " Student('john', 'A', 15),\n", 268 | " Student('jane', 'B', 12),\n", 269 | " Student('dave', 'B', 10),\n", 270 | "]" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": null, 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "from operator import itemgetter, attrgetter\n", 280 | "sorted(student_objects, key=attrgetter('age'), reverse=True)" 281 | ] 282 | }, 283 | { 284 | "cell_type": "markdown", 285 | "metadata": {}, 286 | "source": [ 287 | "# Dictionary" 288 | ] 289 | }, 290 | { 291 | "cell_type": "code", 292 | "execution_count": null, 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "[1,2,3] == [2,1,3]" 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": null, 302 | "metadata": {}, 303 | "outputs": [], 304 | "source": [ 305 | "my_dict = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": null, 311 | "metadata": {}, 312 | "outputs": [], 313 | "source": [ 314 | "my_dict == {2: 'B', 4: 'E', 5: 'A', 1: 'D', 3: 'B'}" 315 | ] 316 | }, 317 | { 318 | "cell_type": "code", 319 | "execution_count": null, 320 | "metadata": {}, 321 | "outputs": [], 322 | "source": [ 323 | "d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}\n", 324 | "sorted(d.items())" 325 | ] 326 | }, 327 | { 328 | "cell_type": "code", 329 | "execution_count": null, 330 | "metadata": {}, 331 | "outputs": [], 332 | "source": [ 333 | "sorted(d.keys())" 334 | ] 335 | }, 336 | { 337 | "cell_type": "code", 338 | "execution_count": null, 339 | "metadata": {}, 340 | "outputs": [], 341 | "source": [ 342 | "from collections import OrderedDict\n", 343 | "d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}\n", 344 | "new_d_num = OrderedDict(sorted(d.items(), key=lambda x: x[1]))\n", 345 | "print(new_d_num)\n", 346 | "new_d_item = OrderedDict(sorted(d.items(), key=lambda x: x[0]))\n", 347 | "print(new_d_item)" 348 | ] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "execution_count": null, 353 | "metadata": {}, 354 | "outputs": [], 355 | "source": [ 356 | "new_d_num == new_d_item" 357 | ] 358 | }, 359 | { 360 | "cell_type": "code", 361 | "execution_count": null, 362 | "metadata": {}, 363 | "outputs": [], 364 | "source": [ 365 | "new_d_num['apple']" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": null, 371 | "metadata": {}, 372 | "outputs": [], 373 | "source": [ 374 | "new_d_num.items()" 375 | ] 376 | }, 377 | { 378 | "cell_type": "markdown", 379 | "metadata": {}, 380 | "source": [ 381 | "# Counter" 382 | ] 383 | }, 384 | { 385 | "cell_type": "code", 386 | "execution_count": null, 387 | "metadata": {}, 388 | "outputs": [], 389 | "source": [ 390 | "from collections import Counter \n", 391 | "c = Counter('gallahad')" 392 | ] 393 | }, 394 | { 395 | "cell_type": "code", 396 | "execution_count": null, 397 | "metadata": {}, 398 | "outputs": [], 399 | "source": [ 400 | "c" 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "execution_count": null, 406 | "metadata": {}, 407 | "outputs": [], 408 | "source": [ 409 | "list(c.elements())" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": null, 415 | "metadata": {}, 416 | "outputs": [], 417 | "source": [ 418 | "c.most_common(2)" 419 | ] 420 | }, 421 | { 422 | "cell_type": "code", 423 | "execution_count": null, 424 | "metadata": {}, 425 | "outputs": [], 426 | "source": [ 427 | "Counter({'red': 4, 'blue': 2}) " 428 | ] 429 | }, 430 | { 431 | "cell_type": "code", 432 | "execution_count": null, 433 | "metadata": {}, 434 | "outputs": [], 435 | "source": [ 436 | "Counter(cats=4, dogs=8) " 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "metadata": {}, 443 | "outputs": [], 444 | "source": [] 445 | } 446 | ], 447 | "metadata": { 448 | "kernelspec": { 449 | "display_name": "Python 3", 450 | "language": "python", 451 | "name": "python3" 452 | }, 453 | "language_info": { 454 | "codemirror_mode": { 455 | "name": "ipython", 456 | "version": 3 457 | }, 458 | "file_extension": ".py", 459 | "mimetype": "text/x-python", 460 | "name": "python", 461 | "nbconvert_exporter": "python", 462 | "pygments_lexer": "ipython3", 463 | "version": "3.7.3" 464 | } 465 | }, 466 | "nbformat": 4, 467 | "nbformat_minor": 4 468 | } 469 | -------------------------------------------------------------------------------- /2020-07-12-python-iterator/iterators.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# What is iterable?" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "def is_iterable(obj):\n", 17 | " return hasattr(obj,'__iter__')\n", 18 | "def has_getitem(obj):\n", 19 | " return hasattr(obj,'__getitem__')" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 2, 25 | "metadata": {}, 26 | "outputs": [ 27 | { 28 | "name": "stdout", 29 | "output_type": "stream", 30 | "text": [ 31 | "It is iterable: True\n", 32 | "It has getitem: True\n" 33 | ] 34 | } 35 | ], 36 | "source": [ 37 | "obj = [1,2,3]\n", 38 | "print(f\"It is iterable: {is_iterable(obj)}\")\n", 39 | "print(f\"It has getitem: {has_getitem(obj)}\")" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": 3, 45 | "metadata": {}, 46 | "outputs": [ 47 | { 48 | "name": "stdout", 49 | "output_type": "stream", 50 | "text": [ 51 | "It is iterable: True\n", 52 | "It has getitem: True\n" 53 | ] 54 | } 55 | ], 56 | "source": [ 57 | "obj = (1,2,3)\n", 58 | "print(f\"It is iterable: {is_iterable(obj)}\")\n", 59 | "print(f\"It has getitem: {has_getitem(obj)}\")" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 4, 65 | "metadata": {}, 66 | "outputs": [ 67 | { 68 | "name": "stdout", 69 | "output_type": "stream", 70 | "text": [ 71 | "It is iterable: True\n", 72 | "It has getitem: True\n" 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "obj = {1:\"a\", 2:\"b\", 3:\"c\"}\n", 78 | "print(f\"It is iterable: {is_iterable(obj)}\")\n", 79 | "print(f\"It has getitem: {has_getitem(obj)}\")" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": 5, 85 | "metadata": {}, 86 | "outputs": [ 87 | { 88 | "name": "stdout", 89 | "output_type": "stream", 90 | "text": [ 91 | "It is iterable: True\n", 92 | "It has getitem: False\n" 93 | ] 94 | } 95 | ], 96 | "source": [ 97 | "dictionary = {1:\"a\", 2:\"b\", 3:\"c\"}\n", 98 | "obj = dictionary.values()\n", 99 | "print(f\"It is iterable: {is_iterable(obj)}\")\n", 100 | "print(f\"It has getitem: {has_getitem(obj)}\")" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 11, 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "name": "stdout", 110 | "output_type": "stream", 111 | "text": [ 112 | "It is iterable: True\n", 113 | "It has getitem: True\n" 114 | ] 115 | } 116 | ], 117 | "source": [ 118 | "obj = range(10)\n", 119 | "print(f\"It is iterable: {is_iterable(obj)}\")\n", 120 | "print(f\"It has getitem: {has_getitem(obj)}\")" 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": {}, 126 | "source": [ 127 | "# Let's write an iterator" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 36, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "class MyIter:\n", 137 | " def __init__(self, max_value):\n", 138 | " self.value = 0\n", 139 | " self.max_value = max_value\n", 140 | " def __next__(self):\n", 141 | " if self.value < self.max_value:\n", 142 | " self.value += 1\n", 143 | " return self.value\n", 144 | " else:\n", 145 | " raise StopIteration" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": 37, 151 | "metadata": {}, 152 | "outputs": [], 153 | "source": [ 154 | "my_iter = MyIter(3)" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "my_iter.__next__()" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": null, 169 | "metadata": {}, 170 | "outputs": [], 171 | "source": [ 172 | "my_iter.__next__()" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "my_iter.__next__()" 182 | ] 183 | }, 184 | { 185 | "cell_type": "markdown", 186 | "metadata": {}, 187 | "source": [ 188 | "# Is it iterable?" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "class MyIter:\n", 198 | " def __init__(self, max_value):\n", 199 | " self.value = 0\n", 200 | " self.max_value = max_value\n", 201 | " def __next__(self):\n", 202 | " if self.value < self.max_value:\n", 203 | " self.value += 1\n", 204 | " return self.value\n", 205 | " else:\n", 206 | " raise StopIteration\n", 207 | " def __iter__(self):\n", 208 | " return self" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": 41, 214 | "metadata": {}, 215 | "outputs": [ 216 | { 217 | "name": "stdout", 218 | "output_type": "stream", 219 | "text": [ 220 | "It is iterable: True\n", 221 | "It has getitem: False\n" 222 | ] 223 | } 224 | ], 225 | "source": [ 226 | "obj = MyIter(10)\n", 227 | "print(f\"It is iterable: {is_iterable(obj)}\")\n", 228 | "print(f\"It has getitem: {has_getitem(obj)}\")" 229 | ] 230 | }, 231 | { 232 | "cell_type": "markdown", 233 | "metadata": {}, 234 | "source": [ 235 | "# What is the iterator of an Iterator?" 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": 47, 241 | "metadata": {}, 242 | "outputs": [ 243 | { 244 | "data": { 245 | "text/plain": [ 246 | "" 247 | ] 248 | }, 249 | "execution_count": 47, 250 | "metadata": {}, 251 | "output_type": "execute_result" 252 | } 253 | ], 254 | "source": [ 255 | "the_iter = iter([1,2,3])\n", 256 | "the_iter" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": 48, 262 | "metadata": {}, 263 | "outputs": [ 264 | { 265 | "data": { 266 | "text/plain": [ 267 | "" 268 | ] 269 | }, 270 | "execution_count": 48, 271 | "metadata": {}, 272 | "output_type": "execute_result" 273 | } 274 | ], 275 | "source": [ 276 | "iter(the_iter)" 277 | ] 278 | }, 279 | { 280 | "cell_type": "markdown", 281 | "metadata": {}, 282 | "source": [ 283 | "# Can we use it in a for loop?" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": 40, 289 | "metadata": {}, 290 | "outputs": [ 291 | { 292 | "name": "stdout", 293 | "output_type": "stream", 294 | "text": [ 295 | "1\n", 296 | "2\n", 297 | "3\n", 298 | "4\n", 299 | "5\n", 300 | "6\n", 301 | "7\n", 302 | "8\n", 303 | "9\n", 304 | "10\n" 305 | ] 306 | } 307 | ], 308 | "source": [ 309 | "for item in MyIter(10):\n", 310 | " print(item)" 311 | ] 312 | }, 313 | { 314 | "cell_type": "markdown", 315 | "metadata": {}, 316 | "source": [ 317 | "# Extra: Let's mess around with `__getitem__`" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": 49, 323 | "metadata": {}, 324 | "outputs": [], 325 | "source": [ 326 | "my_list = [1,2,3]" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": 50, 332 | "metadata": {}, 333 | "outputs": [ 334 | { 335 | "data": { 336 | "text/plain": [ 337 | "1" 338 | ] 339 | }, 340 | "execution_count": 50, 341 | "metadata": {}, 342 | "output_type": "execute_result" 343 | } 344 | ], 345 | "source": [ 346 | "my_list[0]" 347 | ] 348 | }, 349 | { 350 | "cell_type": "code", 351 | "execution_count": 51, 352 | "metadata": {}, 353 | "outputs": [ 354 | { 355 | "data": { 356 | "text/plain": [ 357 | "1" 358 | ] 359 | }, 360 | "execution_count": 51, 361 | "metadata": {}, 362 | "output_type": "execute_result" 363 | } 364 | ], 365 | "source": [ 366 | "my_list.__getitem__(0)" 367 | ] 368 | }, 369 | { 370 | "cell_type": "code", 371 | "execution_count": 52, 372 | "metadata": {}, 373 | "outputs": [ 374 | { 375 | "data": { 376 | "text/plain": [ 377 | "[2, 3]" 378 | ] 379 | }, 380 | "execution_count": 52, 381 | "metadata": {}, 382 | "output_type": "execute_result" 383 | } 384 | ], 385 | "source": [ 386 | "my_list[1:]" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 59, 392 | "metadata": {}, 393 | "outputs": [], 394 | "source": [ 395 | "import pandas as pd" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": 87, 401 | "metadata": {}, 402 | "outputs": [], 403 | "source": [ 404 | "df = pd.DataFrame()\n", 405 | "data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}\n", 406 | "df = df.from_dict(data)" 407 | ] 408 | }, 409 | { 410 | "cell_type": "code", 411 | "execution_count": 88, 412 | "metadata": {}, 413 | "outputs": [ 414 | { 415 | "name": "stdout", 416 | "output_type": "stream", 417 | "text": [ 418 | "It is iterable: True\n", 419 | "It has getitem: True\n" 420 | ] 421 | } 422 | ], 423 | "source": [ 424 | "obj = df\n", 425 | "print(f\"It is iterable: {is_iterable(obj)}\")\n", 426 | "print(f\"It has getitem: {has_getitem(obj)}\")" 427 | ] 428 | }, 429 | { 430 | "cell_type": "code", 431 | "execution_count": 92, 432 | "metadata": {}, 433 | "outputs": [ 434 | { 435 | "data": { 436 | "text/plain": [ 437 | "0 3\n", 438 | "1 2\n", 439 | "2 1\n", 440 | "3 0\n", 441 | "Name: col_1, dtype: int64" 442 | ] 443 | }, 444 | "execution_count": 92, 445 | "metadata": {}, 446 | "output_type": "execute_result" 447 | } 448 | ], 449 | "source": [ 450 | "df.__getitem__('col_1')" 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": 94, 456 | "metadata": {}, 457 | "outputs": [ 458 | { 459 | "data": { 460 | "text/plain": [ 461 | "'col_1'" 462 | ] 463 | }, 464 | "execution_count": 94, 465 | "metadata": {}, 466 | "output_type": "execute_result" 467 | } 468 | ], 469 | "source": [ 470 | "iter(df).__next__()" 471 | ] 472 | }, 473 | { 474 | "cell_type": "markdown", 475 | "metadata": {}, 476 | "source": [ 477 | "# Extra: Itertools\n", 478 | "\n", 479 | "https://docs.python.org/3/library/itertools.html" 480 | ] 481 | }, 482 | { 483 | "cell_type": "code", 484 | "execution_count": 95, 485 | "metadata": {}, 486 | "outputs": [], 487 | "source": [ 488 | "import itertools" 489 | ] 490 | }, 491 | { 492 | "cell_type": "code", 493 | "execution_count": 96, 494 | "metadata": {}, 495 | "outputs": [], 496 | "source": [ 497 | "cyc_obj = itertools.cycle([1,2,3])" 498 | ] 499 | }, 500 | { 501 | "cell_type": "code", 502 | "execution_count": 100, 503 | "metadata": {}, 504 | "outputs": [ 505 | { 506 | "data": { 507 | "text/plain": [ 508 | "1" 509 | ] 510 | }, 511 | "execution_count": 100, 512 | "metadata": {}, 513 | "output_type": "execute_result" 514 | } 515 | ], 516 | "source": [ 517 | "cyc_obj.__next__()" 518 | ] 519 | }, 520 | { 521 | "cell_type": "code", 522 | "execution_count": 101, 523 | "metadata": {}, 524 | "outputs": [ 525 | { 526 | "name": "stdout", 527 | "output_type": "stream", 528 | "text": [ 529 | "Hello\n", 530 | "Hello\n", 531 | "Hello\n" 532 | ] 533 | } 534 | ], 535 | "source": [ 536 | "for item in itertools.repeat(\"Hello\", 3):\n", 537 | " print(item)" 538 | ] 539 | }, 540 | { 541 | "cell_type": "code", 542 | "execution_count": null, 543 | "metadata": {}, 544 | "outputs": [], 545 | "source": [] 546 | } 547 | ], 548 | "metadata": { 549 | "kernelspec": { 550 | "display_name": "Python 3", 551 | "language": "python", 552 | "name": "python3" 553 | }, 554 | "language_info": { 555 | "codemirror_mode": { 556 | "name": "ipython", 557 | "version": 3 558 | }, 559 | "file_extension": ".py", 560 | "mimetype": "text/x-python", 561 | "name": "python", 562 | "nbconvert_exporter": "python", 563 | "pygments_lexer": "ipython3", 564 | "version": "3.7.3" 565 | } 566 | }, 567 | "nbformat": 4, 568 | "nbformat_minor": 4 569 | } 570 | --------------------------------------------------------------------------------