├── README.md ├── code_1_2 ├── Deck.py ├── Person.py ├── bit_count.py ├── comb.py ├── dict_invert.py ├── excel_example.py ├── excel_example.xls ├── excel_example_out.py ├── excel_example_out.xls ├── fact_exception.py ├── id_checksum.py ├── id_checksum.xls ├── itb_examples.py ├── local_bar.py ├── local_foo.py ├── long_line.py ├── loop_del.py ├── m35.py ├── max_of_3n.py ├── max_of_3n_raw.py ├── my_sqrt.py ├── my_sqrt_m.py ├── myhello.py ├── mymath.py ├── numpy_ex1.py ├── numpy_ex2.py ├── numpy_ex3.py ├── numpy_ex3_KNMI_20160101_20160630.txt ├── numpy_ex3_KNMI_20160101_20160630_backup.txt ├── numpy_ex3_KNMI_20160601_20160630.txt ├── numpy_ex3_KNMI_20160601_20160630_backup.txt ├── numpy_ex4.png ├── numpy_ex4.py ├── poker_sum.py ├── powerset.py └── prime_sieve.py ├── code_3 ├── Deck.py ├── id_checksum.py ├── id_checksum.xls ├── itb_examples.py ├── prime_sieve.py └── triple_quote.py ├── code_4 ├── KNMI_20160101_20160630.txt ├── KNMI_20160101_20160630_new.csv ├── MyDeck.py ├── MyDeck_generator_expr.py ├── MyDeck_gf.py ├── ascii_format.py ├── co_acc.py ├── dec_memo.py ├── dec_memo_limit.py ├── dec_natural.py ├── dec_time.py ├── earthquake.py ├── earthquake.txt ├── earthquake_data.json ├── earthquake_data_new.json ├── earthquake_data_small.json ├── earthquake_data_small_b.json ├── fact.py ├── fib.py ├── file_bad.py ├── file_basic.py ├── file_basic.txt ├── file_basic_big5_cp950.txt ├── file_basic_removed.txt ├── file_basic_utf8.txt ├── file_remove_blankline.py ├── fl_ctof.py ├── fl_fact.py ├── fl_failed.py ├── fl_odd_fibs.py ├── fl_sq_even.py ├── fl_tph.py ├── frange_class.py ├── frange_gf.py ├── hello_ascii.py ├── hello_big5_cp950.py ├── hello_big5_cp950_shebang.py ├── hello_utf8.py ├── hello_utf8_shebang.py ├── hex.py ├── hf_sum.py ├── knmi.py ├── lex_perm.py ├── local_bar.py ├── local_foo.py ├── m99_format.py ├── max_so_far.py ├── perm.py ├── perm_product.py ├── pickle_rw.py ├── queen_basic.py ├── queen_c++.cpp ├── queen_hettingers.py ├── queen_hettingers_gf.py ├── queen_howell.py ├── queen_test.py ├── scope_basic.py ├── scope_counter.py ├── scope_counter_shared.py ├── scope_default_arg_mutable.py ├── scope_dynamic.py ├── scope_my_sqrt.py ├── scope_sorted.py ├── test_hk.txt ├── tph.py ├── unique_gf.py ├── unique_set.py ├── vase.txt ├── vase_cp950.txt ├── vase_gbk.txt ├── vase_tr.py └── yield_from_basic.py ├── code_5 ├── A_B.py ├── Card.py ├── Deck.py ├── Deck_1.py ├── Deck_2.py ├── Deck_3.py ├── Deck_4.py ├── Fibmemo.py ├── MyDeck.py ├── MyDeck_generator_expr.py ├── MyDeck_gf.py ├── Person.py ├── Person_2.py ├── Person_property.py ├── a.py ├── co_acc.py ├── except_foo_bar.py ├── except_reraise.py ├── except_return.py ├── fact_exception_1.py ├── fact_exception_2.py ├── fact_exception_3.py ├── fact_traditional.py ├── fl_ctof.py ├── fl_fact.py ├── fl_failed.py ├── fl_odd_fibs.py ├── fl_sq_even.py ├── fl_tph.py ├── frange_class.py ├── frange_gf.py ├── futures_process.py ├── lex_perm.py ├── max_so_far.py ├── method_decorator.py ├── mi.py ├── myhello.py ├── myhello2.py ├── myhello3.py ├── mymath.py ├── mymath2.py ├── mymath3.py ├── open_file.py ├── package_example │ ├── __init__.py │ ├── formats │ │ ├── __init__.py │ │ ├── bar.py │ │ ├── bmp.py │ │ ├── foo.py │ │ ├── jpg.py │ │ └── png.py │ ├── gui │ │ ├── __init__.py │ │ ├── canvas.py │ │ └── menu.py │ ├── info.py │ └── tools │ │ ├── __init__.py │ │ ├── bar.py │ │ ├── foo.py │ │ ├── rotate.py │ │ └── xyz │ │ └── __init__.py ├── package_example_main.py ├── perm.py ├── private_name.py ├── queen_basic.py ├── queen_hettingers_gf.py ├── text_big5.txt ├── text_utf16be.txt ├── text_utf8.txt ├── tiger.py ├── tph.py ├── unique_gf.py ├── unique_set.py ├── weather_hsinchu.py ├── weather_hsinchu.py_all_a.txt ├── weather_hsinchu.py_all_b.txt └── while_else.py ├── py01_intro.pdf ├── py02_basic_part1.pdf ├── py02_basic_part2.pdf ├── py02_basic_part3.pdf ├── py02_basic_part4_ex.pdf ├── py03_numeric.pdf ├── py04_container_part1.pdf ├── py04_container_part1b.pdf ├── py04_container_part2.pdf ├── py05_function_1.pdf ├── py05_function_2.pdf ├── py05_function_3.pdf ├── py05_function_4.pdf ├── py06_str_format.pdf ├── py07_file_bytes_encoding.pdf ├── py08_class.pdf ├── py09_module.pdf ├── py10_exception.pdf └── py11_others.pdf /README.md: -------------------------------------------------------------------------------- 1 | # python_book_slides 2 | 《Python程式設計入門》一書的投影片 3 | 4 | 之前曾開設共30小時的Python入門課程,分為5天、每天6小時,製作了一份投影片,以及相關範例程式。 5 | 6 | 內容大致按照拙作《Python程式設計入門》一書的介紹順序,但稍加改動,有所增減,除了投影片(PDF格式),另有相關的原始程式碼檔案。 7 | 8 | 《Python程式設計入門》:http://yehnan.blogspot.tw/2015/03/python_30.html 9 | 10 | 投影片裡的中英文字型分別是新細明體和Arial,各作業系統應已內建,程式碼的字型則採用inconsolata-g。 11 | -------------------------------------------------------------------------------- /code_1_2/Deck.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import random 4 | # from collections import abc 5 | 6 | # class Deck(abc.Sized, object): 7 | class Deck(object): 8 | cards_count = 52 9 | 10 | # spade, heart, diamond, club 11 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 12 | suits_shortname = 'SHDC' 13 | suit_count = 13 14 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 15 | 16 | def __init__(self): 17 | # 0~12 are Spade A~K, 18 | # 13~25 are Heart A~K, 19 | # 26~38 are Diamond A~K, 20 | # 39~51 are Club A~K 21 | # True means not-drawed-yet 22 | self.cards = list(range(Deck.cards_count)) 23 | # print(self.cards) 24 | 25 | def draw(self): 26 | card = '' 27 | if len(self.cards) > 0: 28 | i = random.randrange(len(self.cards)) 29 | card_n = self.cards.pop(i) 30 | q, r = divmod(card_n, Deck.suit_count) 31 | # print(card_n, q, r) 32 | card = ' '.join((Deck.suits[q], Deck.ranks[r])) 33 | 34 | return card 35 | 36 | def __iter__(self): 37 | return self 38 | 39 | def __next__(self): 40 | card = self.draw() 41 | if card != '': 42 | return card 43 | else: 44 | raise StopIteration('Deck is empty') 45 | 46 | # def next(self): 47 | # return self.__next__() 48 | 49 | def __len__(self): 50 | return len(self.cards) 51 | 52 | def __str__(self): 53 | return 'The deck remains %d cards.' % len(self.cards) 54 | 55 | if __name__ == '__main__': 56 | d = Deck() 57 | print(len(d)) 58 | for _ in range(5): 59 | print(d.draw()) 60 | print(len(d)) 61 | 62 | d2 = Deck() 63 | print(d2) 64 | d2.draw() 65 | print(d2) 66 | for card in d2: 67 | print(card) 68 | 69 | # print(next(d2)) 70 | # print(next(d2)) 71 | # print(d2) 72 | # print(issubclass(Deck, abc.Sized)) 73 | 74 | 75 | -------------------------------------------------------------------------------- /code_1_2/Person.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import datetime 4 | 5 | class Person(): 6 | def __init__(self, name, birthyear): 7 | self.name = name 8 | self.birthyear = birthyear 9 | def say(self, msg='Hello'): 10 | print(self.name + ' says ' + msg) 11 | def age(self): 12 | return datetime.datetime.now().year - self.birthyear 13 | 14 | if __name__ == '__main__': 15 | p = Person('John', 2000) 16 | print(p.name, p.birthyear) 17 | p.say() 18 | p.say('it is so hot') 19 | print(p.name + ' is ' + str(p.age()) + ' years old.') 20 | -------------------------------------------------------------------------------- /code_1_2/bit_count.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_1_2/bit_count.py -------------------------------------------------------------------------------- /code_1_2/comb.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | li0 = ['a', 'b', 'c'] 4 | li1 = ['.jpg', '.png', '.bmp'] 5 | result = [] 6 | for x in li0: 7 | if x != 'a': 8 | for y in li1: 9 | if y != '.jpg': 10 | result.append(x + y) 11 | 12 | print(result) 13 | 14 | #### 15 | 16 | result = [x+y for x in li0 if x != 'a' for y in li1 if y != '.jpg'] 17 | 18 | print(result) 19 | -------------------------------------------------------------------------------- /code_1_2/dict_invert.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | d = {'Amy': 45, 'Bob': 50, 'Cathy': 62, 'David': 45, 4 | 'Eason': 63, 'Fred': 78, 'George': 72, 'Helen': 82, 5 | 'Ivan': 100, 'Jason': 98, 'Kevin': 0, 'Laura': 100} 6 | 7 | d2 = {v:k for k,v in d.items()} 8 | 9 | d3 = {} 10 | for k, v in d.items(): 11 | r = v // 10 12 | if r not in d3: 13 | d3[r] = [] 14 | d3[r].append(k) 15 | print(d3) 16 | 17 | #### output: #### 18 | # {0: ['Kevin'], 4: ['David', 'Amy'], 5: ['Bob'], 6: ['Cathy', 'Eason'], 19 | # 7: ['Fred', 'George'], 8: ['Helen'], 9: ['Jason'], 10: ['Ivan', 'Laura']} 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /code_1_2/excel_example.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | import xlrd 4 | 5 | # 開啟既有的Excel檔, 6 | bk = xlrd.open_workbook('excel_example.xls') 7 | print(bk) 8 | print('encoding:', bk.encoding) 9 | print('There are ' + str(bk.nsheets) + ' sheets.') 10 | print('-' * 20); 11 | 12 | for sheet in bk.sheets(): 13 | print(sheet.name, sheet.nrows, 'rows', sheet.ncols, 'cols') 14 | print() 15 | 16 | # 印cell 17 | if sheet.nrows: 18 | for r in range(sheet.nrows): 19 | row = sheet.row(r) 20 | for cell in row: 21 | print(cell, ' ', end='') 22 | print() 23 | print() 24 | 25 | # 印cell.value 26 | if sheet.nrows: 27 | for r in range(sheet.nrows): 28 | for c in range(sheet.ncols): 29 | cell = sheet.cell(r, c) # 30 | print(cell.value, ' ', end='') 31 | print() 32 | 33 | print('-' * 20) 34 | 35 | 36 | -------------------------------------------------------------------------------- /code_1_2/excel_example.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_1_2/excel_example.xls -------------------------------------------------------------------------------- /code_1_2/excel_example_out.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | import xlrd, xlwt 5 | 6 | # 開啟既有的Excel檔, 7 | bk = xlrd.open_workbook('excel_example.xls') 8 | # 只拿出第0個sheet 9 | sheet = bk.sheet_by_index(0) 10 | 11 | print(sheet.name, sheet.nrows, 'rows', sheet.ncols, 'cols') 12 | print() 13 | 14 | if sheet.nrows: 15 | for r in range(sheet.nrows): 16 | for c in range(sheet.ncols): 17 | cell = sheet.cell(r, c) 18 | print(cell.value, ' ', end='') 19 | print() 20 | #### 21 | 22 | # 新增workboot,將要寫入cell 23 | bk_out = xlwt.Workbook() 24 | # 加入一個sheet 25 | sheet_out = bk_out.add_sheet('Sheet1') 26 | 27 | if sheet.nrows: 28 | # 處理第0列 29 | for col_i, cell in enumerate(sheet.row(0)): 30 | sheet_out.write(0, col_i, cell.value) 31 | sheet_out.write(0, sheet.ncols, '平均') 32 | 33 | # 處理其餘的列 34 | for row_i in range(1, sheet.nrows): 35 | total = 0 # 總分 36 | count = 0 # 幾個分數 37 | for col_i, cell in enumerate(sheet.row(row_i)): 38 | sheet_out.write(row_i, col_i, cell.value) 39 | if cell.ctype == xlrd.XL_CELL_NUMBER: 40 | total += cell.value 41 | count += 1 42 | avg = total / count # 平均 43 | 44 | sheet_out.write(row_i, sheet.ncols, avg) 45 | 46 | # 存檔,指定檔名 47 | bk_out.save('excel_example_out.xls') 48 | 49 | 50 | -------------------------------------------------------------------------------- /code_1_2/excel_example_out.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_1_2/excel_example_out.xls -------------------------------------------------------------------------------- /code_1_2/fact_exception.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | def fact(n): 5 | if n < 0: 6 | raise ValueError('Argument must be non-negative') 7 | result = 1 8 | for i in range(1, n+1): 9 | result *= i 10 | return result 11 | 12 | while True: 13 | try: 14 | s = input('input n: ') 15 | sn = int(s) 16 | f = fact(sn) 17 | except TypeError as e: 18 | print('Error: ' + str(e)) 19 | except ValueError as e: 20 | print('Error: ' + str(e)) 21 | except (EOFError, KeyboardInterrupt): 22 | print('\nBye') 23 | break 24 | except Exception: 25 | print('Error: unknown error') 26 | else: 27 | print(str(sn) + '! = ' + str(f)) 28 | # print('%s! = %d' % (s, f)) 29 | 30 | -------------------------------------------------------------------------------- /code_1_2/id_checksum.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | import random 4 | 5 | #### use list to store 6 | # 'A' index is 0, 'B' index is 1, etc.. 'Z' is 25 7 | loc_li = [10, 11, 12, 13, 14, 8 | 15, 16, 17, 34, 18, 9 | 19, 20, 21, 22, 35, 10 | 23, 24, 25, 26, 27, 11 | 28, 29, 32, 30, 31, 12 | 33] 13 | # location is 'A' or 'B' or ... 'Z' 14 | def location_to_number(location): 15 | return loc_li[ord(location) - ord('A')] 16 | 17 | #### use dict to store 18 | loc = {'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 19 | 'F':15, 'G':16, 'H':17, 'I':34, 'J':18, 20 | 'K':19, 'L':20, 'M':21, 'N':22, 'O':35, 21 | 'P':23, 'Q':24, 'R':25, 'S':26, 'T':27, 22 | 'U':28, 'V':29, 'W':32, 'X':30, 'Y':31, 23 | 'Z':33} 24 | 25 | # input an id as str, use the first 9 characters 26 | # to calculate the checksum 27 | def checksum(id): 28 | total = 0 29 | 30 | x = loc[id[0]] 31 | # x = location_to_number(id[0]) 32 | 33 | total += (x % 10) * 9 + (x // 10) 34 | 35 | for i in range(1, 8+1): 36 | total += int(id[i]) * (9-i) 37 | 38 | cksum = total % 10 39 | if cksum != 0: 40 | cksum = 10 - cksum 41 | 42 | return cksum 43 | 44 | # 檢查id是否正確,回傳True或False 45 | def check(id): 46 | return checksum(id) == int(id[9]) 47 | 48 | # location: 'A'~'Z' 49 | # gender: 1 male, 2 female 50 | def random_id(location, gender): 51 | id = location + str(gender) 52 | for _ in range(2, 8+1): 53 | n = random.randint(0, 9) 54 | id += str(n) 55 | 56 | id += str(checksum(id)) 57 | 58 | return id 59 | 60 | 61 | if __name__ == '__main__': 62 | import sys 63 | if len(sys.argv) == 1: 64 | print('Usage: ' + __file__ + ' [-c id] or [-g [male/female]]') 65 | elif len(sys.argv) >= 2: 66 | if sys.argv[1] == '-c': 67 | if len(sys.argv) == 3: 68 | print('Verification: ', end='') 69 | if check(sys.argv[2]): 70 | print('PASS') 71 | else: 72 | print('FAIL') 73 | cksum = checksum(sys.argv[2]) 74 | print('Correct: ' + sys.argv[2][:9] + str(cksum)) 75 | else: 76 | print('Usage: ' + __file__ + ' -c id') 77 | elif sys.argv[1] == '-g': 78 | loc = chr(ord('A') + random.randint(0, 25)) 79 | gender = random.randint(1, 2) 80 | print(random_id(loc, gender)) 81 | else: 82 | print('Usage: ' + __file__ + ' [-c id] or [-g [male/female]]') 83 | # id_valid = ('A123456789', 'S212305438') 84 | # for id in id_valid: 85 | # if check(id) == False: 86 | # print('fail', id) 87 | 88 | # id_invalid = ('A123456781', 'S212305432') 89 | # for id in id_invalid: 90 | # if check(id) == True: 91 | # print('fail', id) 92 | 93 | # for i in range(26): 94 | # loc = chr(ord('A') + i) 95 | # if location_to_number(loc) != mapping[loc]: 96 | # print('fail', loc) 97 | 98 | -------------------------------------------------------------------------------- /code_1_2/id_checksum.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_1_2/id_checksum.xls -------------------------------------------------------------------------------- /code_1_2/itb_examples.py: -------------------------------------------------------------------------------- 1 | 2 | #### 3 | def product(iterable, start=1): 4 | result = start 5 | for x in iterable: 6 | result *= x 7 | return result 8 | 9 | a = range(1, 10+1) 10 | b = [2, 3, 4, 5] 11 | c = [1.1, 3.5, 5.6] 12 | print(product(a, 0.1)) 13 | print(product(b)) 14 | print(product(c)) 15 | 16 | #### 17 | def my_factorial(n): 18 | return product(range(2, n+1)) 19 | 20 | from math import factorial 21 | print('6! is ' + str(my_factorial(6))) 22 | print('math.factorial: ' + str(factorial(6))) 23 | print('10! is ' + str(my_factorial(10))) 24 | print('math.factorial: ' + str(factorial(10))) 25 | print('15! is ' + str(my_factorial(15))) 26 | print('math.factorial: ' + str(factorial(15))) 27 | 28 | #### 29 | def cumulative_sum(iterable, start=0): 30 | result = [] 31 | acc = start 32 | for x in iterable: 33 | acc += x 34 | result.append(acc) 35 | return result 36 | 37 | 38 | print(cumulative_sum(range(10+1))) 39 | print(cumulative_sum(range(0, 1000, 100))) 40 | 41 | #### 42 | def unique(iterable): 43 | result = [] 44 | for x in iterable: 45 | if x not in result: 46 | result.append(x) 47 | return result 48 | 49 | 50 | print(unique([1, 2, 1, 3, 2, 5, 5, 6, 1])) # [1, 2, 3, 5, 6] 51 | print(unique([1, 2, 1, 3, 2, 5])) # [1, 2, 3, 5] 52 | print(unique(range(10))) 53 | 54 | #### 55 | def duplicate(iterable): 56 | fst = [] 57 | snd = [] 58 | for x in iterable: 59 | if x not in fst: 60 | fst.append(x) 61 | elif x not in snd: 62 | snd.append(x) 63 | else: 64 | pass 65 | return snd 66 | 67 | print(duplicate([1, 2, 6, 1, 3, 2, 5])) 68 | print(duplicate(range(10))) 69 | print(duplicate([1, 1, 3, 1, 3, 3, 1, 2, 1, 5, 2])) 70 | 71 | #### 72 | def group(iterable, size): 73 | result = [] 74 | li = list(iterable) 75 | length = len(li) 76 | for i in range(0, length, size): 77 | result.append(li[i:i+size]) 78 | return result 79 | 80 | print(group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) 81 | # [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 82 | 83 | print(group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)) 84 | # [[1, 2, 3, 4], [5, 6, 7, 8], [9]] 85 | 86 | print(group(range(20), 5)) 87 | 88 | #### 89 | def flatten(iterable): 90 | result = [] 91 | for x in iterable: 92 | result.extend(x) 93 | return result 94 | 95 | 96 | print(flatten([[0, 1, 2], [3, 4, 5], [6], [7, 8], [9]])) 97 | print(flatten([[0, 1], [3, 5], [6], [7, 8], [9]])) 98 | 99 | #### 100 | 101 | 102 | 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /code_1_2/local_bar.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | y = 100 5 | 6 | def bar(x): 7 | print(y) 8 | y = x + 10 9 | return y 10 | 11 | bar(3) 12 | -------------------------------------------------------------------------------- /code_1_2/local_foo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | x = 3 5 | 6 | def foo(): 7 | x += 10 8 | print(x) 9 | 10 | foo() 11 | print(x) 12 | -------------------------------------------------------------------------------- /code_1_2/long_line.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | a, b, c, d, e, f = 1, 2, 3, 4 ,5, 6 5 | if a > 0 and b > 1 and c > 2 and \ 6 | d > 3 and e > 4 and f > 5: 7 | print('hello') 8 | 9 | if (a > 0 and b > 1 and c > 2 and 10 | d > 3 and e > 4 and f > 5): 11 | print('hello') 12 | -------------------------------------------------------------------------------- /code_1_2/loop_del.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | li = [0, 1, 2, 3, 4, 5] 4 | 5 | for i in range(len(li)): 6 | if li[i] % 2 == 0: 7 | del li[i] 8 | 9 | print(li) 10 | -------------------------------------------------------------------------------- /code_1_2/m35.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Problem 1: Multiples of 3 and 5 4 | # https://projecteuler.net/problem=1 5 | 6 | # 7 | def m35_a(n): 8 | result = 0 9 | for i in range(1, n): 10 | if i % 3 == 0 or i % 5 == 0: 11 | result += i 12 | return result 13 | 14 | # 15 | def m35_b(n): 16 | return sum(i for i in range(1, n) if i%3 == 0 or i%5 == 0) 17 | 18 | # 19 | def m35_c(n): 20 | sm3 = sum(range(3, n, 3)) 21 | sm5 = sum(range(5, n, 5)) 22 | sm15 = sum(range(3*5, n, 3*5)) 23 | return sm3 + sm5 - sm15 24 | 25 | # 26 | def m35_d(n): 27 | def sub(n): 28 | a, b = 3, 5 29 | while a < n or b < n: 30 | if a < b: 31 | yield a 32 | a += 3 33 | elif a == b: 34 | yield a 35 | a += 3 36 | b += 5 37 | elif a > b: 38 | yield b 39 | b += 5 40 | return sum(sub(n)) 41 | 42 | # 43 | def m35_e(n): 44 | from operator import add 45 | from functools import reduce 46 | def is_m35(n): 47 | return n%3 == 0 or n%5 == 0 48 | return reduce(add, filter(is_m35, range(1, n)), 0) 49 | 50 | # 51 | def test(): 52 | m35all = [m35_a, m35_b, m35_c, m35_d, m35_e] 53 | n = 10 54 | for f in m35all: 55 | if f(n) != 23: 56 | return 'Fail' 57 | break 58 | # 59 | n = 1000 60 | a = m35_a(n) 61 | b = m35_b(n) 62 | c = m35_c(n) 63 | d = m35_d(n) 64 | e = m35_e(n) 65 | if a == b == c == d == e: 66 | return 'Pass' 67 | else: 68 | return 'Fail' 69 | 70 | def main(): 71 | return m35_a(1000) 72 | 73 | if __name__ == '__main__': 74 | import sys 75 | if len(sys.argv) >= 2 and sys.argv[1] == 'test': 76 | print(test()) 77 | else: 78 | print(main()) 79 | 80 | -------------------------------------------------------------------------------- /code_1_2/max_of_3n.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | import random 4 | 5 | def max_of_3n(a, b, c): 6 | x = None 7 | if a < b: # 縮排零層 8 | if b < c: # 縮排一層 9 | x = c # 縮排二層 10 | else: # 縮排一層 11 | x = b # 縮排二層 12 | else: # 縮排零層 13 | if a < c: # 縮排一層 14 | x = c # 縮排二層 15 | else: # 縮排一層 16 | x = a # 縮排二層 17 | # 最後x會是a、b、c中最大的 18 | return x 19 | 20 | def max_of_3n_b(a, b, c): 21 | return (c if b < c else b) if a < b else (c if a < c else a) 22 | 23 | if __name__ == '__main__': 24 | for _ in range(100): 25 | a = random.randint(1, 100) 26 | b = random.randint(1, 100) 27 | c = random.randint(1, 100) 28 | m1 = max(a, b, c) 29 | m2 = max_of_3n(a, b, c) 30 | m3 = max_of_3n_b(a, b, c) 31 | if m1 != m2: 32 | print('fail', a, b, c, m1, m2) 33 | if m1 != m3: 34 | print('fail', a, b, c, m1, m3) 35 | -------------------------------------------------------------------------------- /code_1_2/max_of_3n_raw.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a, b, c = 3, 5, 7; x = None 4 | if a < b: # 縮排零層 5 | if b < c: # 縮排一層 6 | x = c # 縮排二層 7 | else: # 縮排一層 8 | x = b # 縮排二層 9 | else: # 縮排零層 10 | if a < c: # 縮排一層 11 | x = c # 縮排二層 12 | else: # 縮排一層 13 | x = a # 縮排二層 14 | # 最後x會是a、b、c中最大的 15 | print(x) 16 | -------------------------------------------------------------------------------- /code_1_2/my_sqrt.py: -------------------------------------------------------------------------------- 1 | 2 | diff = 0.00001 3 | def is_ok(n, ans): 4 | return abs(ans**2 - n) < diff 5 | def get_better(n, ans): 6 | return ((float(n) / ans) + ans) / 2 7 | def my_sqrt(n): 8 | ans = 1 9 | while not is_ok(n, ans): 10 | ans = get_better(n, ans) 11 | return ans 12 | 13 | if __name__ == '__main__': 14 | import math 15 | print(my_sqrt(9), math.sqrt(9)) 16 | print(my_sqrt(2), math.sqrt(2)) 17 | print(my_sqrt(3), math.sqrt(3)) 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /code_1_2/my_sqrt_m.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def my_sqrt(n, diff=0.00001): 4 | def is_ok(n, ans, diff): 5 | return abs(ans**2 - n) < diff 6 | 7 | def get_better(n, ans): 8 | print(((float(n) / ans) + ans) / 2) 9 | return ((float(n) / ans) + ans) / 2 10 | 11 | ans = 1 12 | while not is_ok(n, ans, diff): 13 | ans = get_better(n, ans) 14 | return ans 15 | 16 | if __name__ == '__main__': 17 | import math 18 | print(my_sqrt(9), math.sqrt(9)) 19 | print(my_sqrt(2), math.sqrt(2)) 20 | print(my_sqrt(3), math.sqrt(3)) 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /code_1_2/myhello.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import mymath 4 | 5 | print('pi is ' + str(mymath.pi)) 6 | print('gcd of 24 and 16 is ' + str(mymath.gcd(24, 16))) 7 | print('factorial of 6 is ' + str(mymath.factorial(6))) 8 | 9 | if __name__ == '__main__': 10 | print('myhello as main program') 11 | else: 12 | print('myhello as module') 13 | 14 | -------------------------------------------------------------------------------- /code_1_2/mymath.py: -------------------------------------------------------------------------------- 1 | 2 | pi = 3.14 3 | 4 | def gcd(a, b): 5 | while b: 6 | a, b = b, a%b 7 | return a 8 | 9 | def factorial(n): 10 | result = 1 11 | for i in range(1, n+1): 12 | result *= i 13 | return result 14 | 15 | if __name__ == '__main__': 16 | print('mymath as main program') 17 | else: 18 | print('mymath as module') 19 | 20 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import numpy as np 4 | 5 | # Python's list and * 6 | print([1, 2, 3, 4] * 3) 7 | print() 8 | 9 | # numpy's array and * 10 | print(np.arange(5)) 11 | print(np.arange(5) * 3) 12 | print() 13 | 14 | def numpysum(n): 15 | a = np.arange(n) ** 2 16 | b = np.arange(n) ** 3 17 | c = a + b 18 | return c 19 | 20 | print(numpysum(5)) 21 | 22 | 23 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex2.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | import numpy as np 4 | 5 | a = np.arange(5) 6 | print("Element's type is", a.dtype) 7 | 8 | # 維度 9 | print("Shape is", a.shape) 10 | print() 11 | 12 | # 矩陣 13 | from numpy import array, arange 14 | 15 | m1 = array([[7, 8, 9], arange(3), [4, 5, 6]]) 16 | print("Element's type is", m1.dtype) 17 | print("Shape is", m1.shape) 18 | print(m1) 19 | print() 20 | 21 | m2 = array([[1, 2, 3], arange(3), [4, 5, 6]]) 22 | print(m2) 23 | print() 24 | 25 | m3 = m1 * m2 # not matrix multiplication 26 | print(m3) 27 | print() 28 | 29 | m4 = np.dot(m1, m2) # 3.5 should support @ 30 | print(m4) 31 | print() 32 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex3.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | import numpy as np 4 | import sys 5 | 6 | def to_float(x): 7 | return float(x.strip() or np.nan) 8 | 9 | # to_float = lambda x: float(x.strip() or np.nan) 10 | 11 | fname = 'numpy_ex3_KNMI_20160601_20160630.txt' 12 | 13 | avg_temp, min_temp, max_temp = np.loadtxt(fname, 14 | delimiter=',', usecols=(2, 3, 4), unpack=True, 15 | converters={2: to_float, 3: to_float, 4: to_float}) * 0.1 16 | 17 | print('min', min_temp) 18 | print('max', max_temp) 19 | print('avg', avg_temp) 20 | print("# Records", len(min_temp), len(max_temp), len(avg_temp)) 21 | print("Minimum", np.nanmin(min_temp)) 22 | print("Maximum", np.nanmax(max_temp)) 23 | print("Average", np.nanmin(avg_temp)) 24 | 25 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex3_KNMI_20160101_20160630.txt: -------------------------------------------------------------------------------- 1 | 215,20160101, 49, -5, 81 2 | 215,20160102, 62, 49, 73 3 | 215,20160103, 72, 53, 89 4 | 215,20160104, 65, 45, 78 5 | 215,20160105, 69, 63, 77 6 | 215,20160106, 46, 36, 66 7 | 215,20160107, 64, 42, 87 8 | 215,20160108, 60, 16, 89 9 | 215,20160109, 60, 17, 85 10 | 215,20160110, 69, 46, 87 11 | 215,20160111, 55, 34, 76 12 | 215,20160112, 68, 55, 79 13 | 215,20160113, 56, 23, 76 14 | 215,20160114, 41, 26, 66 15 | 215,20160115, 30, 8, 50 16 | 215,20160116, 42, 6, 62 17 | 215,20160117, -1, -43, 35 18 | 215,20160118, -23, -42, 2 19 | 215,20160119, -12, -66, 23 20 | 215,20160120, 20, -32, 60 21 | 215,20160121, -6, -47, 13 22 | 215,20160122, 20, -20, 84 23 | 215,20160123, 79, 63, 101 24 | 215,20160124, 87, 56, 118 25 | 215,20160125, 108, 84, 139 26 | 215,20160126, 90, 54, 107 27 | 215,20160127, 108, 82, 119 28 | 215,20160128, 68, 51, 89 29 | 215,20160129, 94, 65, 107 30 | 215,20160130, 77, 55, 98 31 | 215,20160131, 76, 57, 109 32 | 215,20160201, 112, 101, 121 33 | 215,20160202, 87, 65, 108 34 | 215,20160203, 56, 37, 70 35 | 215,20160204, 59, 22, 79 36 | 215,20160205, 90, 41, 109 37 | 215,20160206, 97, 86, 108 38 | 215,20160207, 84, 63, 121 39 | 215,20160208, 87, 71, 99 40 | 215,20160209, 60, 41, 83 41 | 215,20160210, 58, 39, 80 42 | 215,20160211, 41, -11, 76 43 | 215,20160212, 27, -26, 61 44 | 215,20160213, 20, -17, 41 45 | 215,20160214, 25, 19, 31 46 | 215,20160215, 24, -34, 66 47 | 215,20160216, 2, -51, 60 48 | 215,20160217, -12, -49, 36 49 | 215,20160218, 11, -38, 26 50 | 215,20160219, 42, -28, 84 51 | 215,20160220, 85, 51, 106 52 | 215,20160221, 104, 87, 113 53 | 215,20160222, 70, 42, 110 54 | 215,20160223, 50, 23, 77 55 | 215,20160224, 24, -17, 67 56 | 215,20160225, 25, -7, 54 57 | 215,20160226, 29, 9, 58 58 | 215,20160227, 30, 5, 63 59 | 215,20160228, 28, -7, 67 60 | 215,20160229, 15, -36, 64 61 | 215,20160301, 34, -49, 88 62 | 215,20160302, 55, 26, 90 63 | 215,20160303, 37, -1, 77 64 | 215,20160304, 22, -22, 65 65 | 215,20160305, 23, -36, 79 66 | 215,20160306, 33, -9, 68 67 | 215,20160307, 27, -2, 60 68 | 215,20160308, 44, -3, 76 69 | 215,20160309, 53, 25, 84 70 | 215,20160310, 45, -7, 88 71 | 215,20160311, 41, 7, 84 72 | 215,20160312, 40, -6, 93 73 | 215,20160313, 41, -3, 90 74 | 215,20160314, 42, -2, 91 75 | 215,20160315, 49, -14, 79 76 | 215,20160316, 51, 16, 95 77 | 215,20160317, 56, 14, 112 78 | 215,20160318, 56, 32, 73 79 | 215,20160319, 64, 54, 80 80 | 215,20160320, 66, 32, 93 81 | 215,20160321, 72, 62, 89 82 | 215,20160322, 73, 42, 100 83 | 215,20160323, 76, 59, 97 84 | 215,20160324, 79, 59, 105 85 | 215,20160325, 66, 3, 97 86 | 215,20160326, 94, -1, 150 87 | 215,20160327, 87, 64, 129 88 | 215,20160328, 92, 76, 114 89 | 215,20160329, 82, 58, 111 90 | 215,20160330, 80, 51, 104 91 | 215,20160331, 77, 36, 121 92 | 215,20160401, 68, -6, 134 93 | 215,20160402, 103, 67, 128 94 | 215,20160403, 139, 116, 173 95 | 215,20160404, 120, 82, 150 96 | 215,20160405, 94, 67, 120 97 | 215,20160406, 85, 46, 109 98 | 215,20160407, 76, 38, 98 99 | 215,20160408, 60, 10, 113 100 | 215,20160409, 92, 17, 149 101 | 215,20160410, 102, 45, 143 102 | 215,20160411, 131, 79, 180 103 | 215,20160412, 109, 49, 159 104 | 215,20160413, 97, 39, 153 105 | 215,20160414, 106, 35, 162 106 | 215,20160415, 101, 83, 132 107 | 215,20160416, 78, 49, 104 108 | 215,20160417, 63, 10, 104 109 | 215,20160418, 83, 8, 122 110 | 215,20160419, 88, 18, 122 111 | 215,20160420, 79, 0, 135 112 | 215,20160421, 100, 36, 153 113 | 215,20160422, 87, 64, 117 114 | 215,20160423, 63, 32, 95 115 | 215,20160424, 52, 11, 88 116 | 215,20160425, 57, 13, 86 117 | 215,20160426, 55, 30, 84 118 | 215,20160427, 60, 30, 87 119 | 215,20160428, 48, -1, 85 120 | 215,20160429, 79, 43, 112 121 | 215,20160430, 71, 13, 102 122 | 215,20160501, 66, -6, 123 123 | 215,20160502, 104, 0, 165 124 | 215,20160503, 88, 29, 119 125 | 215,20160504, 97, 16, 161 126 | 215,20160505, 128, 44, 180 127 | 215,20160506, 157, 95, 230 128 | 215,20160507, 182, 86, 252 129 | 215,20160508, 197, 130, 250 130 | 215,20160509, 197, 141, 239 131 | 215,20160510, 181, 156, 209 132 | 215,20160511, 197, 141, 247 133 | 215,20160512, 199, 144, 248 134 | 215,20160513, 144, 86, 215 135 | 215,20160514, 88, 67, 118 136 | 215,20160515, 85, 54, 117 137 | 215,20160516, 90, 59, 123 138 | 215,20160517, 122, 64, 161 139 | 215,20160518, 129, 89, 178 140 | 215,20160519, 126, 100, 168 141 | 215,20160520, 136, 111, 168 142 | 215,20160521, 169, 111, 225 143 | 215,20160522, 139, 117, 173 144 | 215,20160523, 117, 104, 135 145 | 215,20160524, 109, 98, 134 146 | 215,20160525, 114, 73, 151 147 | 215,20160526, 123, 51, 173 148 | 215,20160527, 158, 111, 208 149 | 215,20160528, 168, 104, 209 150 | 215,20160529, 166, 140, 203 151 | 215,20160530, 137, 131, 147 152 | 215,20160531, 177, 131, 219 153 | 215,20160601, 157, 130, 194 154 | 215,20160602, 130, 121, 141 155 | 215,20160603, 137, 122, 157 156 | 215,20160604, 184, 127, 242 157 | 215,20160605, 172, 110, 221 158 | 215,20160606, 172, 110, 223 159 | 215,20160607, 196, 136, 256 160 | 215,20160608, 147, 120, 184 161 | 215,20160609, 136, 90, 165 162 | 215,20160610, 148, 84, 193 163 | 215,20160611, 154, 125, 198 164 | 215,20160612, 164, 127, 215 165 | 215,20160613, 152, 144, 173 166 | 215,20160614, 150, 116, 183 167 | 215,20160615, 146, 96, 187 168 | 215,20160616, 151, 97, 194 169 | 215,20160617, 154, 122, 188 170 | 215,20160618, 132, 97, 159 171 | 215,20160619, 155, 117, 195 172 | 215,20160620, 157, 144, 165 173 | 215,20160621, 157, 115, 193 174 | 215,20160622, 197, 113, 250 175 | 215,20160623, 205, 179, 267 176 | 215,20160624, 175, 118, 205 177 | 215,20160625, 146, 97, 185 178 | 215,20160626, 154, 116, 179 179 | 215,20160627, 151, 110, 178 180 | 215,20160628, 151, 92, 202 181 | 215,20160629, 158, 135, 198 182 | 215,20160630, 161, 146, 182 183 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex3_KNMI_20160101_20160630_backup.txt: -------------------------------------------------------------------------------- 1 | # BRON: KONINKLIJK NEDERLANDS METEOROLOGISCH INSTITUUT (KNMI) 2 | # Opmerking: door stationsverplaatsingen en veranderingen in waarneemmethodieken zijn deze tijdreeksen van dagwaarden mogelijk inhomogeen! Dat betekent dat deze reeks van gemeten waarden niet geschikt is voor trendanalyse. Voor studies naar klimaatverandering verwijzen we naar de gehomogeniseerde reeks maandtemperaturen van De Bilt of de Centraal Nederland Temperatuur . 3 | # 4 | # 5 | # STN LON(east) LAT(north) ALT(m) NAME 6 | # 215: 4.437 52.141 -1.10 VOORSCHOTEN 7 | # 8 | # YYYYMMDD = Datum (YYYY=jaar MM=maand DD=dag); 9 | # TG = Etmaalgemiddelde temperatuur (in 0.1 graden Celsius); 10 | # TN = Minimum temperatuur (in 0.1 graden Celsius); 11 | # TX = Maximum temperatuur (in 0.1 graden Celsius); 12 | # 13 | # STN,YYYYMMDD, TG, TN, TX 14 | # 15 | 215,20160101, 49, -5, 81 16 | 215,20160102, 62, 49, 73 17 | 215,20160103, 72, 53, 89 18 | 215,20160104, 65, 45, 78 19 | 215,20160105, 69, 63, 77 20 | 215,20160106, 46, 36, 66 21 | 215,20160107, 64, 42, 87 22 | 215,20160108, 60, 16, 89 23 | 215,20160109, 60, 17, 85 24 | 215,20160110, 69, 46, 87 25 | 215,20160111, 55, 34, 76 26 | 215,20160112, 68, 55, 79 27 | 215,20160113, 56, 23, 76 28 | 215,20160114, 41, 26, 66 29 | 215,20160115, 30, 8, 50 30 | 215,20160116, 42, 6, 62 31 | 215,20160117, -1, -43, 35 32 | 215,20160118, -23, -42, 2 33 | 215,20160119, -12, -66, 23 34 | 215,20160120, 20, -32, 60 35 | 215,20160121, -6, -47, 13 36 | 215,20160122, 20, -20, 84 37 | 215,20160123, 79, 63, 101 38 | 215,20160124, 87, 56, 118 39 | 215,20160125, 108, 84, 139 40 | 215,20160126, 90, 54, 107 41 | 215,20160127, 108, 82, 119 42 | 215,20160128, 68, 51, 89 43 | 215,20160129, 94, 65, 107 44 | 215,20160130, 77, 55, 98 45 | 215,20160131, 76, 57, 109 46 | 215,20160201, 112, 101, 121 47 | 215,20160202, 87, 65, 108 48 | 215,20160203, 56, 37, 70 49 | 215,20160204, 59, 22, 79 50 | 215,20160205, 90, 41, 109 51 | 215,20160206, 97, 86, 108 52 | 215,20160207, 84, 63, 121 53 | 215,20160208, 87, 71, 99 54 | 215,20160209, 60, 41, 83 55 | 215,20160210, 58, 39, 80 56 | 215,20160211, 41, -11, 76 57 | 215,20160212, 27, -26, 61 58 | 215,20160213, 20, -17, 41 59 | 215,20160214, 25, 19, 31 60 | 215,20160215, 24, -34, 66 61 | 215,20160216, 2, -51, 60 62 | 215,20160217, -12, -49, 36 63 | 215,20160218, 11, -38, 26 64 | 215,20160219, 42, -28, 84 65 | 215,20160220, 85, 51, 106 66 | 215,20160221, 104, 87, 113 67 | 215,20160222, 70, 42, 110 68 | 215,20160223, 50, 23, 77 69 | 215,20160224, 24, -17, 67 70 | 215,20160225, 25, -7, 54 71 | 215,20160226, 29, 9, 58 72 | 215,20160227, 30, 5, 63 73 | 215,20160228, 28, -7, 67 74 | 215,20160229, 15, -36, 64 75 | 215,20160301, 34, -49, 88 76 | 215,20160302, 55, 26, 90 77 | 215,20160303, 37, -1, 77 78 | 215,20160304, 22, -22, 65 79 | 215,20160305, 23, -36, 79 80 | 215,20160306, 33, -9, 68 81 | 215,20160307, 27, -2, 60 82 | 215,20160308, 44, -3, 76 83 | 215,20160309, 53, 25, 84 84 | 215,20160310, 45, -7, 88 85 | 215,20160311, 41, 7, 84 86 | 215,20160312, 40, -6, 93 87 | 215,20160313, 41, -3, 90 88 | 215,20160314, 42, -2, 91 89 | 215,20160315, 49, -14, 79 90 | 215,20160316, 51, 16, 95 91 | 215,20160317, 56, 14, 112 92 | 215,20160318, 56, 32, 73 93 | 215,20160319, 64, 54, 80 94 | 215,20160320, 66, 32, 93 95 | 215,20160321, 72, 62, 89 96 | 215,20160322, 73, 42, 100 97 | 215,20160323, 76, 59, 97 98 | 215,20160324, 79, 59, 105 99 | 215,20160325, 66, 3, 97 100 | 215,20160326, 94, -1, 150 101 | 215,20160327, 87, 64, 129 102 | 215,20160328, 92, 76, 114 103 | 215,20160329, 82, 58, 111 104 | 215,20160330, 80, 51, 104 105 | 215,20160331, 77, 36, 121 106 | 215,20160401, 68, -6, 134 107 | 215,20160402, 103, 67, 128 108 | 215,20160403, 139, 116, 173 109 | 215,20160404, 120, 82, 150 110 | 215,20160405, 94, 67, 120 111 | 215,20160406, 85, 46, 109 112 | 215,20160407, 76, 38, 98 113 | 215,20160408, 60, 10, 113 114 | 215,20160409, 92, 17, 149 115 | 215,20160410, 102, 45, 143 116 | 215,20160411, 131, 79, 180 117 | 215,20160412, 109, 49, 159 118 | 215,20160413, 97, 39, 153 119 | 215,20160414, 106, 35, 162 120 | 215,20160415, 101, 83, 132 121 | 215,20160416, 78, 49, 104 122 | 215,20160417, 63, 10, 104 123 | 215,20160418, 83, 8, 122 124 | 215,20160419, 88, 18, 122 125 | 215,20160420, 79, 0, 135 126 | 215,20160421, 100, 36, 153 127 | 215,20160422, 87, 64, 117 128 | 215,20160423, 63, 32, 95 129 | 215,20160424, 52, 11, 88 130 | 215,20160425, 57, 13, 86 131 | 215,20160426, 55, 30, 84 132 | 215,20160427, 60, 30, 87 133 | 215,20160428, 48, -1, 85 134 | 215,20160429, 79, 43, 112 135 | 215,20160430, 71, 13, 102 136 | 215,20160501, 66, -6, 123 137 | 215,20160502, 104, 0, 165 138 | 215,20160503, 88, 29, 119 139 | 215,20160504, 97, 16, 161 140 | 215,20160505, 128, 44, 180 141 | 215,20160506, 157, 95, 230 142 | 215,20160507, 182, 86, 252 143 | 215,20160508, 197, 130, 250 144 | 215,20160509, 197, 141, 239 145 | 215,20160510, 181, 156, 209 146 | 215,20160511, 197, 141, 247 147 | 215,20160512, 199, 144, 248 148 | 215,20160513, 144, 86, 215 149 | 215,20160514, 88, 67, 118 150 | 215,20160515, 85, 54, 117 151 | 215,20160516, 90, 59, 123 152 | 215,20160517, 122, 64, 161 153 | 215,20160518, 129, 89, 178 154 | 215,20160519, 126, 100, 168 155 | 215,20160520, 136, 111, 168 156 | 215,20160521, 169, 111, 225 157 | 215,20160522, 139, 117, 173 158 | 215,20160523, 117, 104, 135 159 | 215,20160524, 109, 98, 134 160 | 215,20160525, 114, 73, 151 161 | 215,20160526, 123, 51, 173 162 | 215,20160527, 158, 111, 208 163 | 215,20160528, 168, 104, 209 164 | 215,20160529, 166, 140, 203 165 | 215,20160530, 137, 131, 147 166 | 215,20160531, 177, 131, 219 167 | 215,20160601, 157, 130, 194 168 | 215,20160602, 130, 121, 141 169 | 215,20160603, 137, 122, 157 170 | 215,20160604, 184, 127, 242 171 | 215,20160605, 172, 110, 221 172 | 215,20160606, 172, 110, 223 173 | 215,20160607, 196, 136, 256 174 | 215,20160608, 147, 120, 184 175 | 215,20160609, 136, 90, 165 176 | 215,20160610, 148, 84, 193 177 | 215,20160611, 154, 125, 198 178 | 215,20160612, 164, 127, 215 179 | 215,20160613, 152, 144, 173 180 | 215,20160614, 150, 116, 183 181 | 215,20160615, 146, 96, 187 182 | 215,20160616, 151, 97, 194 183 | 215,20160617, 154, 122, 188 184 | 215,20160618, 132, 97, 159 185 | 215,20160619, 155, 117, 195 186 | 215,20160620, 157, 144, 165 187 | 215,20160621, 157, 115, 193 188 | 215,20160622, 197, 113, 250 189 | 215,20160623, 205, 179, 267 190 | 215,20160624, 175, 118, 205 191 | 215,20160625, 146, 97, 185 192 | 215,20160626, 154, 116, 179 193 | 215,20160627, 151, 110, 178 194 | 215,20160628, 151, 92, 202 195 | 215,20160629, 158, 135, 198 196 | 215,20160630, 161, 146, 182 197 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex3_KNMI_20160601_20160630.txt: -------------------------------------------------------------------------------- 1 | 215,20160601, 157, 130, 194 2 | 215,20160602, 130, 121, 141 3 | 215,20160603, 137, 122, 157 4 | 215,20160604, 184, 127, 242 5 | 215,20160605, 172, 110, 221 6 | 215,20160606, 172, 110, 223 7 | 215,20160607, 196, 136, 256 8 | 215,20160608, 147, 120, 184 9 | 215,20160609, 136, 90, 165 10 | 215,20160610, 148, 84, 193 11 | 215,20160611, 154, 125, 198 12 | 215,20160612, 164, 127, 215 13 | 215,20160613, 152, 144, 173 14 | 215,20160614, 150, 116, 183 15 | 215,20160615, 146, 96, 187 16 | 215,20160616, 151, 97, 194 17 | 215,20160617, 154, 122, 188 18 | 215,20160618, 132, 97, 159 19 | 215,20160619, 155, 117, 195 20 | 215,20160620, 157, 144, 165 21 | 215,20160621, 157, 115, 193 22 | 215,20160622, 197, 113, 250 23 | 215,20160623, 205, 179, 267 24 | 215,20160624, 175, 118, 205 25 | 215,20160625, 146, 97, 185 26 | 215,20160626, 154, 116, 179 27 | 215,20160627, 151, 110, 178 28 | 215,20160628, 151, 92, 202 29 | 215,20160629, 158, 135, 198 30 | 215,20160630, 161, 146, 182 31 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex3_KNMI_20160601_20160630_backup.txt: -------------------------------------------------------------------------------- 1 | # BRON: KONINKLIJK NEDERLANDS METEOROLOGISCH INSTITUUT (KNMI) 2 | # Opmerking: door stationsverplaatsingen en veranderingen in waarneemmethodieken zijn deze tijdreeksen van dagwaarden mogelijk inhomogeen! Dat betekent dat deze reeks van gemeten waarden niet geschikt is voor trendanalyse. Voor studies naar klimaatverandering verwijzen we naar de gehomogeniseerde reeks maandtemperaturen van De Bilt of de Centraal Nederland Temperatuur . 3 | # 4 | # 5 | # STN LON(east) LAT(north) ALT(m) NAME 6 | # 215: 4.437 52.141 -1.10 VOORSCHOTEN 7 | # 8 | # YYYYMMDD = Datum (YYYY=jaar MM=maand DD=dag); 9 | # TG = Etmaalgemiddelde temperatuur (in 0.1 graden Celsius); 10 | # TN = Minimum temperatuur (in 0.1 graden Celsius); 11 | # TX = Maximum temperatuur (in 0.1 graden Celsius); 12 | # 13 | # STN,YYYYMMDD, TG, TN, TX 14 | # 15 | 215,20160601, 157, 130, 194 16 | 215,20160602, 130, 121, 141 17 | 215,20160603, 137, 122, 157 18 | 215,20160604, 184, 127, 242 19 | 215,20160605, 172, 110, 221 20 | 215,20160606, 172, 110, 223 21 | 215,20160607, 196, 136, 256 22 | 215,20160608, 147, 120, 184 23 | 215,20160609, 136, 90, 165 24 | 215,20160610, 148, 84, 193 25 | 215,20160611, 154, 125, 198 26 | 215,20160612, 164, 127, 215 27 | 215,20160613, 152, 144, 173 28 | 215,20160614, 150, 116, 183 29 | 215,20160615, 146, 96, 187 30 | 215,20160616, 151, 97, 194 31 | 215,20160617, 154, 122, 188 32 | 215,20160618, 132, 97, 159 33 | 215,20160619, 155, 117, 195 34 | 215,20160620, 157, 144, 165 35 | 215,20160621, 157, 115, 193 36 | 215,20160622, 197, 113, 250 37 | 215,20160623, 205, 179, 267 38 | 215,20160624, 175, 118, 205 39 | 215,20160625, 146, 97, 185 40 | 215,20160626, 154, 116, 179 41 | 215,20160627, 151, 110, 178 42 | 215,20160628, 151, 92, 202 43 | 215,20160629, 158, 135, 198 44 | 215,20160630, 161, 146, 182 45 | -------------------------------------------------------------------------------- /code_1_2/numpy_ex4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_1_2/numpy_ex4.png -------------------------------------------------------------------------------- /code_1_2/numpy_ex4.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | import numpy as np 5 | from scipy import interpolate 6 | import matplotlib.pyplot as plt 7 | 8 | x = np.linspace(-18, 18, 36) 9 | noise = 0.1 * np.random.random(len(x)) 10 | # 使用sinc,加上一些noise 11 | signal = np.sinc(x) + noise 12 | 13 | # interp1d: create linear or cubic interpolation function 14 | interpolated = interpolate.interp1d(x, signal) # linear 15 | x2 = np.linspace(-18, 18, 36*5) # 5倍 16 | y = interpolated(x2) 17 | 18 | cubic = interpolate.interp1d(x, signal, kind="cubic") 19 | y2 = cubic(x2) 20 | 21 | plt.plot(x, signal, 'o', label="data") 22 | plt.plot(x2, y, '-', label="linear") 23 | plt.plot(x2, y2, '--', lw=2, label="cubic") 24 | plt.legend() 25 | #plt.show() 26 | plt.savefig('numpy_ex4.png') 27 | -------------------------------------------------------------------------------- /code_1_2/poker_sum.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | total = 0 4 | for x in range(1, 13+1): 5 | total += x 6 | total *= 4 7 | 8 | print(total) 9 | -------------------------------------------------------------------------------- /code_1_2/powerset.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #### powerset, all subsets of a set #### 4 | def powerset(li): 5 | ps = [] 6 | for n in range(0, 2**len(li)): 7 | sub = [] 8 | x = n 9 | for i in range(len(li)): 10 | if x & 0x1: 11 | sub.append(li[i]) 12 | x >>= 1 13 | ps.append(sub) 14 | return ps 15 | 16 | if __name__ == '__main__': 17 | ps = powerset([1, 2, 3]) 18 | for x in ps: 19 | print(x) 20 | print('Size is ' + str(len(ps))) 21 | -------------------------------------------------------------------------------- /code_1_2/prime_sieve.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #### generate a set containing prime numbers from 2 to n #### 4 | def prime_sieve(n): 5 | primes = set(range(2, n+1)) 6 | for i in range(2, (n+1+1) // 2): 7 | if i in primes: 8 | m = 2 9 | while i*m <= n: 10 | primes.discard(i*m) 11 | m += 1 12 | return primes 13 | 14 | #### this is not a good algorithm to check prime numbers #### 15 | def is_prime(n): 16 | for i in range(2, n): 17 | if n % i == 0: 18 | return False 19 | return True 20 | 21 | 22 | -------------------------------------------------------------------------------- /code_3/Deck.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import random 4 | # from collections import abc 5 | 6 | # class Deck(abc.Sized, object): 7 | class Deck(object): 8 | cards_count = 52 9 | 10 | # spade, heart, diamond, club 11 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 12 | suits_shortname = 'SHDC' 13 | suit_count = 13 14 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 15 | 16 | def __init__(self): 17 | # 0~12 are Spade A~K, 18 | # 13~25 are Heart A~K, 19 | # 26~38 are Diamond A~K, 20 | # 39~51 are Club A~K 21 | # True means not-drawed-yet 22 | self.cards = list(range(Deck.cards_count)) 23 | # print(self.cards) 24 | 25 | def draw(self): 26 | card = '' 27 | if len(self.cards) > 0: 28 | i = random.randrange(len(self.cards)) 29 | card_n = self.cards.pop(i) 30 | q, r = divmod(card_n, Deck.suit_count) 31 | # print(card_n, q, r) 32 | card = ' '.join((Deck.suits[q], Deck.ranks[r])) 33 | 34 | return card 35 | 36 | def __iter__(self): 37 | return self 38 | 39 | def __next__(self): 40 | card = self.draw() 41 | if card != '': 42 | return card 43 | else: 44 | raise StopIteration('Deck is empty') 45 | 46 | def next(self): 47 | return self.__next__() 48 | 49 | def __len__(self): 50 | return len(self.cards) 51 | 52 | def __str__(self): 53 | return 'The deck remains %d cards.' % len(self.cards) 54 | 55 | if __name__ == '__main__': 56 | d = Deck() 57 | print(len(d)) 58 | for _ in range(5): 59 | print(d.draw()) 60 | print(len(d)) 61 | 62 | d2 = Deck() 63 | print(d2) 64 | d2.draw() 65 | print(d2) 66 | for card in d2: 67 | print(card) 68 | 69 | # print(next(d2)) 70 | # print(next(d2)) 71 | # print(d2) 72 | # print(issubclass(Deck, abc.Sized)) 73 | 74 | 75 | -------------------------------------------------------------------------------- /code_3/id_checksum.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | import random 5 | 6 | #### use list to store 7 | # 'A' index is 0, 'B' index is 1, etc.. 'Z' is 25 8 | loc_li = [10, 11, 12, 13, 14, 9 | 15, 16, 17, 34, 18, 10 | 19, 20, 21, 22, 35, 11 | 23, 24, 25, 26, 27, 12 | 28, 29, 32, 30, 31, 13 | 33] 14 | # location is 'A' or 'B' or ... 'Z' 15 | def location_to_number(location): 16 | return loc_li[ord(location) - ord('A')] 17 | 18 | #### use dict to store 19 | loc_d = {'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 20 | 'F':15, 'G':16, 'H':17, 'I':34, 'J':18, 21 | 'K':19, 'L':20, 'M':21, 'N':22, 'O':35, 22 | 'P':23, 'Q':24, 'R':25, 'S':26, 'T':27, 23 | 'U':28, 'V':29, 'W':32, 'X':30, 'Y':31, 24 | 'Z':33} 25 | 26 | # input an id as str, use the first 9 characters 27 | # to calculate the checksum 28 | def checksum(id): 29 | total = 0 30 | 31 | x = loc_d[id[0]] 32 | # x = location_to_number(id[0]) 33 | 34 | total += (x % 10) * 9 + (x // 10) 35 | 36 | for i in range(1, 8+1): 37 | total += int(id[i]) * (9-i) 38 | 39 | cksum = total % 10 40 | if cksum != 0: 41 | cksum = 10 - cksum 42 | 43 | return cksum 44 | 45 | # 檢查id是否正確,回傳True或False 46 | def check(id): 47 | return checksum(id) == int(id[9]) 48 | 49 | # location: 'A'~'Z' 50 | # gender: 1 male, 2 female 51 | def random_id(location, gender): 52 | id = location + str(gender) 53 | for _ in range(2, 8+1): 54 | n = random.randint(0, 9) 55 | id += str(n) 56 | 57 | id += str(checksum(id)) 58 | 59 | return id 60 | 61 | 62 | if __name__ == '__main__': 63 | import sys 64 | if len(sys.argv) == 1: 65 | print('Usage: ' + __file__ + ' [-c id] or [-g [male/female]]') 66 | elif len(sys.argv) >= 2: 67 | if sys.argv[1] == '-c': 68 | if len(sys.argv) == 3: 69 | print('Verification: ', end='') 70 | if check(sys.argv[2]): 71 | print('PASS') 72 | else: 73 | print('FAIL') 74 | cksum = checksum(sys.argv[2]) 75 | print('Correct: ' + sys.argv[2][:9] + str(cksum)) 76 | else: 77 | print('Usage: ' + __file__ + ' -c id') 78 | elif sys.argv[1] == '-g': 79 | loc = chr(ord('A') + random.randint(0, 25)) 80 | gender = random.randint(1, 2) 81 | print(random_id(loc, gender)) 82 | else: 83 | print('Usage: ' + __file__ + ' [-c id] or [-g [male/female]]') 84 | # id_valid = ('A123456789', 'S212305438') 85 | # for id in id_valid: 86 | # if check(id) == False: 87 | # print('fail', id) 88 | 89 | # id_invalid = ('A123456781', 'S212305432') 90 | # for id in id_invalid: 91 | # if check(id) == True: 92 | # print('fail', id) 93 | 94 | # for i in range(26): 95 | # loc = chr(ord('A') + i) 96 | # if location_to_number(loc) != mapping[loc]: 97 | # print('fail', loc) 98 | 99 | -------------------------------------------------------------------------------- /code_3/id_checksum.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_3/id_checksum.xls -------------------------------------------------------------------------------- /code_3/itb_examples.py: -------------------------------------------------------------------------------- 1 | 2 | #### 3 | def product(iterable, start=1): 4 | result = start 5 | for x in iterable: 6 | result *= x 7 | return result 8 | 9 | a = range(1, 10+1) 10 | b = [2, 3, 4, 5] 11 | c = [1.1, 3.5, 5.6] 12 | print(product(a, 0.1)) 13 | print(product(b)) 14 | print(product(c)) 15 | 16 | #### 17 | def my_factorial(n): 18 | return product(range(2, n+1)) 19 | 20 | from math import factorial 21 | print('6! is ' + str(my_factorial(6))) 22 | print('math.factorial: ' + str(factorial(6))) 23 | print('10! is ' + str(my_factorial(10))) 24 | print('math.factorial: ' + str(factorial(10))) 25 | print('15! is ' + str(my_factorial(15))) 26 | print('math.factorial: ' + str(factorial(15))) 27 | 28 | #### 29 | def cumulative_sum(iterable, start=0): 30 | result = [] 31 | acc = start 32 | for x in iterable: 33 | acc += x 34 | result.append(acc) 35 | return result 36 | 37 | 38 | print(cumulative_sum(range(10+1))) 39 | print(cumulative_sum(range(0, 1000, 100))) 40 | 41 | #### 42 | # can be replaced by set 43 | def unique(iterable): 44 | result = [] 45 | for x in iterable: 46 | if x not in result: 47 | result.append(x) 48 | return result 49 | 50 | 51 | print(unique([1, 2, 1, 3, 2, 5, 5, 6, 1])) # [1, 2, 3, 5, 6] 52 | print(unique([1, 2, 1, 3, 2, 5])) # [1, 2, 3, 5] 53 | print(unique(range(10))) 54 | 55 | #### 56 | def duplicate(iterable): 57 | fst = [] 58 | snd = [] 59 | for x in iterable: 60 | if x not in fst: 61 | fst.append(x) 62 | elif x not in snd: 63 | snd.append(x) 64 | else: 65 | pass 66 | return snd 67 | 68 | print(duplicate([1, 2, 6, 1, 3, 2, 5])) 69 | print(duplicate(range(10))) 70 | print(duplicate([1, 1, 3, 1, 3, 3, 1, 2, 1, 5, 2])) 71 | 72 | #### 73 | def group(iterable, size): 74 | result = [] 75 | li = list(iterable) 76 | length = len(li) 77 | for i in range(0, length, size): 78 | result.append(li[i:i+size]) 79 | return result 80 | 81 | print(group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) 82 | # [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 83 | 84 | print(group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)) 85 | # [[1, 2, 3, 4], [5, 6, 7, 8], [9]] 86 | 87 | print(group(range(20), 5)) 88 | 89 | #### 90 | def flatten(iterable): 91 | result = [] 92 | for x in iterable: 93 | result.extend(x) 94 | return result 95 | 96 | 97 | print(flatten([[0, 1, 2], [3, 4, 5], [6], [7, 8], [9]])) 98 | print(flatten([[0, 1], [3, 5], [6], [7, 8], [9]])) 99 | 100 | #### 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /code_3/prime_sieve.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #### generate a set containing prime numbers from 2 to n #### 4 | def prime_sieve(n): 5 | primes = set(range(2, n+1)) 6 | for i in range(2, (n+1+1) // 2): 7 | if i in primes: 8 | m = 2 9 | while i*m <= n: 10 | primes.discard(i*m) 11 | m += 1 12 | return primes 13 | 14 | #### this is not a good algorithm to check prime numbers #### 15 | def is_prime(n): 16 | for i in range(2, n): 17 | if n % i == 0: 18 | return False 19 | return True 20 | 21 | 22 | -------------------------------------------------------------------------------- /code_3/triple_quote.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = '''abc def 4 | ghi jkl mno 5 | pqr\nstuvw''' 6 | 7 | print(s) 8 | -------------------------------------------------------------------------------- /code_4/KNMI_20160101_20160630.txt: -------------------------------------------------------------------------------- 1 | # BRON: KONINKLIJK NEDERLANDS METEOROLOGISCH INSTITUUT (KNMI) 2 | # Opmerking: door stationsverplaatsingen en veranderingen in waarneemmethodieken zijn deze tijdreeksen van dagwaarden mogelijk inhomogeen! Dat betekent dat deze reeks van gemeten waarden niet geschikt is voor trendanalyse. Voor studies naar klimaatverandering verwijzen we naar de gehomogeniseerde reeks maandtemperaturen van De Bilt of de Centraal Nederland Temperatuur . 3 | # 4 | # 5 | # STN LON(east) LAT(north) ALT(m) NAME 6 | # 215: 4.437 52.141 -1.10 VOORSCHOTEN 7 | # 8 | # YYYYMMDD = Datum (YYYY=jaar MM=maand DD=dag); 9 | # TG = Etmaalgemiddelde temperatuur (in 0.1 graden Celsius); 10 | # TN = Minimum temperatuur (in 0.1 graden Celsius); 11 | # TX = Maximum temperatuur (in 0.1 graden Celsius); 12 | # 13 | # STN,YYYYMMDD, TG, TN, TX 14 | # 15 | 215,20160101, 49, -5, 81 16 | 215,20160102, 62, 49, 73 17 | 215,20160103, 72, 53, 89 18 | 215,20160104, 65, 45, 78 19 | 215,20160105, 69, 63, 77 20 | 215,20160106, 46, 36, 66 21 | 215,20160107, 64, 42, 87 22 | 215,20160108, 60, 16, 89 23 | 215,20160109, 60, 17, 85 24 | 215,20160110, 69, 46, 87 25 | 215,20160111, 55, 34, 76 26 | 215,20160112, 68, 55, 79 27 | 215,20160113, 56, 23, 76 28 | 215,20160114, 41, 26, 66 29 | 215,20160115, 30, 8, 50 30 | 215,20160116, 42, 6, 62 31 | 215,20160117, -1, -43, 35 32 | 215,20160118, -23, -42, 2 33 | 215,20160119, -12, -66, 23 34 | 215,20160120, 20, -32, 60 35 | 215,20160121, -6, -47, 13 36 | 215,20160122, 20, -20, 84 37 | 215,20160123, 79, 63, 101 38 | 215,20160124, 87, 56, 118 39 | 215,20160125, 108, 84, 139 40 | 215,20160126, 90, 54, 107 41 | 215,20160127, 108, 82, 119 42 | 215,20160128, 68, 51, 89 43 | 215,20160129, 94, 65, 107 44 | 215,20160130, 77, 55, 98 45 | 215,20160131, 76, 57, 109 46 | 215,20160201, 112, 101, 121 47 | 215,20160202, 87, 65, 108 48 | 215,20160203, 56, 37, 70 49 | 215,20160204, 59, 22, 79 50 | 215,20160205, 90, 41, 109 51 | 215,20160206, 97, 86, 108 52 | 215,20160207, 84, 63, 121 53 | 215,20160208, 87, 71, 99 54 | 215,20160209, 60, 41, 83 55 | 215,20160210, 58, 39, 80 56 | 215,20160211, 41, -11, 76 57 | 215,20160212, 27, -26, 61 58 | 215,20160213, 20, -17, 41 59 | 215,20160214, 25, 19, 31 60 | 215,20160215, 24, -34, 66 61 | 215,20160216, 2, -51, 60 62 | 215,20160217, -12, -49, 36 63 | 215,20160218, 11, -38, 26 64 | 215,20160219, 42, -28, 84 65 | 215,20160220, 85, 51, 106 66 | 215,20160221, 104, 87, 113 67 | 215,20160222, 70, 42, 110 68 | 215,20160223, 50, 23, 77 69 | 215,20160224, 24, -17, 67 70 | 215,20160225, 25, -7, 54 71 | 215,20160226, 29, 9, 58 72 | 215,20160227, 30, 5, 63 73 | 215,20160228, 28, -7, 67 74 | 215,20160229, 15, -36, 64 75 | 215,20160301, 34, -49, 88 76 | 215,20160302, 55, 26, 90 77 | 215,20160303, 37, -1, 77 78 | 215,20160304, 22, -22, 65 79 | 215,20160305, 23, -36, 79 80 | 215,20160306, 33, -9, 68 81 | 215,20160307, 27, -2, 60 82 | 215,20160308, 44, -3, 76 83 | 215,20160309, 53, 25, 84 84 | 215,20160310, 45, -7, 88 85 | 215,20160311, 41, 7, 84 86 | 215,20160312, 40, -6, 93 87 | 215,20160313, 41, -3, 90 88 | 215,20160314, 42, -2, 91 89 | 215,20160315, 49, -14, 79 90 | 215,20160316, 51, 16, 95 91 | 215,20160317, 56, 14, 112 92 | 215,20160318, 56, 32, 73 93 | 215,20160319, 64, 54, 80 94 | 215,20160320, 66, 32, 93 95 | 215,20160321, 72, 62, 89 96 | 215,20160322, 73, 42, 100 97 | 215,20160323, 76, 59, 97 98 | 215,20160324, 79, 59, 105 99 | 215,20160325, 66, 3, 97 100 | 215,20160326, 94, -1, 150 101 | 215,20160327, 87, 64, 129 102 | 215,20160328, 92, 76, 114 103 | 215,20160329, 82, 58, 111 104 | 215,20160330, 80, 51, 104 105 | 215,20160331, 77, 36, 121 106 | 215,20160401, 68, -6, 134 107 | 215,20160402, 103, 67, 128 108 | 215,20160403, 139, 116, 173 109 | 215,20160404, 120, 82, 150 110 | 215,20160405, 94, 67, 120 111 | 215,20160406, 85, 46, 109 112 | 215,20160407, 76, 38, 98 113 | 215,20160408, 60, 10, 113 114 | 215,20160409, 92, 17, 149 115 | 215,20160410, 102, 45, 143 116 | 215,20160411, 131, 79, 180 117 | 215,20160412, 109, 49, 159 118 | 215,20160413, 97, 39, 153 119 | 215,20160414, 106, 35, 162 120 | 215,20160415, 101, 83, 132 121 | 215,20160416, 78, 49, 104 122 | 215,20160417, 63, 10, 104 123 | 215,20160418, 83, 8, 122 124 | 215,20160419, 88, 18, 122 125 | 215,20160420, 79, 0, 135 126 | 215,20160421, 100, 36, 153 127 | 215,20160422, 87, 64, 117 128 | 215,20160423, 63, 32, 95 129 | 215,20160424, 52, 11, 88 130 | 215,20160425, 57, 13, 86 131 | 215,20160426, 55, 30, 84 132 | 215,20160427, 60, 30, 87 133 | 215,20160428, 48, -1, 85 134 | 215,20160429, 79, 43, 112 135 | 215,20160430, 71, 13, 102 136 | 215,20160501, 66, -6, 123 137 | 215,20160502, 104, 0, 165 138 | 215,20160503, 88, 29, 119 139 | 215,20160504, 97, 16, 161 140 | 215,20160505, 128, 44, 180 141 | 215,20160506, 157, 95, 230 142 | 215,20160507, 182, 86, 252 143 | 215,20160508, 197, 130, 250 144 | 215,20160509, 197, 141, 239 145 | 215,20160510, 181, 156, 209 146 | 215,20160511, 197, 141, 247 147 | 215,20160512, 199, 144, 248 148 | 215,20160513, 144, 86, 215 149 | 215,20160514, 88, 67, 118 150 | 215,20160515, 85, 54, 117 151 | 215,20160516, 90, 59, 123 152 | 215,20160517, 122, 64, 161 153 | 215,20160518, 129, 89, 178 154 | 215,20160519, 126, 100, 168 155 | 215,20160520, 136, 111, 168 156 | 215,20160521, 169, 111, 225 157 | 215,20160522, 139, 117, 173 158 | 215,20160523, 117, 104, 135 159 | 215,20160524, 109, 98, 134 160 | 215,20160525, 114, 73, 151 161 | 215,20160526, 123, 51, 173 162 | 215,20160527, 158, 111, 208 163 | 215,20160528, 168, 104, 209 164 | 215,20160529, 166, 140, 203 165 | 215,20160530, 137, 131, 147 166 | 215,20160531, 177, 131, 219 167 | 215,20160601, 157, 130, 194 168 | 215,20160602, 130, 121, 141 169 | 215,20160603, 137, 122, 157 170 | 215,20160604, 184, 127, 242 171 | 215,20160605, 172, 110, 221 172 | 215,20160606, 172, 110, 223 173 | 215,20160607, 196, 136, 256 174 | 215,20160608, 147, 120, 184 175 | 215,20160609, 136, 90, 165 176 | 215,20160610, 148, 84, 193 177 | 215,20160611, 154, 125, 198 178 | 215,20160612, 164, 127, 215 179 | 215,20160613, 152, 144, 173 180 | 215,20160614, 150, 116, 183 181 | 215,20160615, 146, 96, 187 182 | 215,20160616, 151, 97, 194 183 | 215,20160617, 154, 122, 188 184 | 215,20160618, 132, 97, 159 185 | 215,20160619, 155, 117, 195 186 | 215,20160620, 157, 144, 165 187 | 215,20160621, 157, 115, 193 188 | 215,20160622, 197, 113, 250 189 | 215,20160623, 205, 179, 267 190 | 215,20160624, 175, 118, 205 191 | 215,20160625, 146, 97, 185 192 | 215,20160626, 154, 116, 179 193 | 215,20160627, 151, 110, 178 194 | 215,20160628, 151, 92, 202 195 | 215,20160629, 158, 135, 198 196 | 215,20160630, 161, 146, 182 197 | -------------------------------------------------------------------------------- /code_4/KNMI_20160101_20160630_new.csv: -------------------------------------------------------------------------------- 1 | YYYY,MM,DD,Min,MAX,AVG 2 | 2016,1,1,-0.5,4.9,8.1 3 | 2016,1,2,4.9,6.2,7.3 4 | 2016,1,3,5.3,7.2,8.9 5 | 2016,1,4,4.5,6.5,7.8 6 | 2016,1,5,6.3,6.9,7.7 7 | 2016,1,6,3.6,4.6,6.6 8 | 2016,1,7,4.2,6.4,8.7 9 | 2016,1,8,1.6,6.0,8.9 10 | 2016,1,9,1.7,6.0,8.5 11 | 2016,1,10,4.6,6.9,8.7 12 | 2016,1,11,3.4,5.5,7.6 13 | 2016,1,12,5.5,6.8,7.9 14 | 2016,1,13,2.3,5.6,7.6 15 | 2016,1,14,2.6,4.1,6.6 16 | 2016,1,15,0.8,3.0,5.0 17 | 2016,1,16,0.6,4.2,6.2 18 | 2016,1,17,-4.3,-0.1,3.5 19 | 2016,1,18,-4.2,-2.3,0.2 20 | 2016,1,19,-6.6,-1.2,2.3 21 | 2016,1,20,-3.2,2.0,6.0 22 | 2016,1,21,-4.7,-0.6,1.3 23 | 2016,1,22,-2.0,2.0,8.4 24 | 2016,1,23,6.3,7.9,10.1 25 | 2016,1,24,5.6,8.7,11.8 26 | 2016,1,25,8.4,10.8,13.9 27 | 2016,1,26,5.4,9.0,10.7 28 | 2016,1,27,8.2,10.8,11.9 29 | 2016,1,28,5.1,6.8,8.9 30 | 2016,1,29,6.5,9.4,10.7 31 | 2016,1,30,5.5,7.7,9.8 32 | 2016,1,31,5.7,7.6,10.9 33 | 2016,2,1,10.1,11.2,12.1 34 | 2016,2,2,6.5,8.7,10.8 35 | 2016,2,3,3.7,5.6,7.0 36 | 2016,2,4,2.2,5.9,7.9 37 | 2016,2,5,4.1,9.0,10.9 38 | 2016,2,6,8.6,9.7,10.8 39 | 2016,2,7,6.3,8.4,12.1 40 | 2016,2,8,7.1,8.7,9.9 41 | 2016,2,9,4.1,6.0,8.3 42 | 2016,2,10,3.9,5.8,8.0 43 | 2016,2,11,-1.1,4.1,7.6 44 | 2016,2,12,-2.6,2.7,6.1 45 | 2016,2,13,-1.7,2.0,4.1 46 | 2016,2,14,1.9,2.5,3.1 47 | 2016,2,15,-3.4,2.4,6.6 48 | 2016,2,16,-5.1,0.2,6.0 49 | 2016,2,17,-4.9,-1.2,3.6 50 | 2016,2,18,-3.8,1.1,2.6 51 | 2016,2,19,-2.8,4.2,8.4 52 | 2016,2,20,5.1,8.5,10.6 53 | 2016,2,21,8.7,10.4,11.3 54 | 2016,2,22,4.2,7.0,11.0 55 | 2016,2,23,2.3,5.0,7.7 56 | 2016,2,24,-1.7,2.4,6.7 57 | 2016,2,25,-0.7,2.5,5.4 58 | 2016,2,26,0.9,2.9,5.8 59 | 2016,2,27,0.5,3.0,6.3 60 | 2016,2,28,-0.7,2.8,6.7 61 | 2016,2,29,-3.6,1.5,6.4 62 | 2016,3,1,-4.9,3.4,8.8 63 | 2016,3,2,2.6,5.5,9.0 64 | 2016,3,3,-0.1,3.7,7.7 65 | 2016,3,4,-2.2,2.2,6.5 66 | 2016,3,5,-3.6,2.3,7.9 67 | 2016,3,6,-0.9,3.3,6.8 68 | 2016,3,7,-0.2,2.7,6.0 69 | 2016,3,8,-0.3,4.4,7.6 70 | 2016,3,9,2.5,5.3,8.4 71 | 2016,3,10,-0.7,4.5,8.8 72 | 2016,3,11,0.7,4.1,8.4 73 | 2016,3,12,-0.6,4.0,9.3 74 | 2016,3,13,-0.3,4.1,9.0 75 | 2016,3,14,-0.2,4.2,9.1 76 | 2016,3,15,-1.4,4.9,7.9 77 | 2016,3,16,1.6,5.1,9.5 78 | 2016,3,17,1.4,5.6,11.2 79 | 2016,3,18,3.2,5.6,7.3 80 | 2016,3,19,5.4,6.4,8.0 81 | 2016,3,20,3.2,6.6,9.3 82 | 2016,3,21,6.2,7.2,8.9 83 | 2016,3,22,4.2,7.3,10.0 84 | 2016,3,23,5.9,7.6,9.7 85 | 2016,3,24,5.9,7.9,10.5 86 | 2016,3,25,0.3,6.6,9.7 87 | 2016,3,26,-0.1,9.4,15.0 88 | 2016,3,27,6.4,8.7,12.9 89 | 2016,3,28,7.6,9.2,11.4 90 | 2016,3,29,5.8,8.2,11.1 91 | 2016,3,30,5.1,8.0,10.4 92 | 2016,3,31,3.6,7.7,12.1 93 | 2016,4,1,-0.6,6.8,13.4 94 | 2016,4,2,6.7,10.3,12.8 95 | 2016,4,3,11.6,13.9,17.3 96 | 2016,4,4,8.2,12.0,15.0 97 | 2016,4,5,6.7,9.4,12.0 98 | 2016,4,6,4.6,8.5,10.9 99 | 2016,4,7,3.8,7.6,9.8 100 | 2016,4,8,1.0,6.0,11.3 101 | 2016,4,9,1.7,9.2,14.9 102 | 2016,4,10,4.5,10.2,14.3 103 | 2016,4,11,7.9,13.1,18.0 104 | 2016,4,12,4.9,10.9,15.9 105 | 2016,4,13,3.9,9.7,15.3 106 | 2016,4,14,3.5,10.6,16.2 107 | 2016,4,15,8.3,10.1,13.2 108 | 2016,4,16,4.9,7.8,10.4 109 | 2016,4,17,1.0,6.3,10.4 110 | 2016,4,18,0.8,8.3,12.2 111 | 2016,4,19,1.8,8.8,12.2 112 | 2016,4,20,0.0,7.9,13.5 113 | 2016,4,21,3.6,10.0,15.3 114 | 2016,4,22,6.4,8.7,11.7 115 | 2016,4,23,3.2,6.3,9.5 116 | 2016,4,24,1.1,5.2,8.8 117 | 2016,4,25,1.3,5.7,8.6 118 | 2016,4,26,3.0,5.5,8.4 119 | 2016,4,27,3.0,6.0,8.7 120 | 2016,4,28,-0.1,4.8,8.5 121 | 2016,4,29,4.3,7.9,11.2 122 | 2016,4,30,1.3,7.1,10.2 123 | 2016,5,1,-0.6,6.6,12.3 124 | 2016,5,2,0.0,10.4,16.5 125 | 2016,5,3,2.9,8.8,11.9 126 | 2016,5,4,1.6,9.7,16.1 127 | 2016,5,5,4.4,12.8,18.0 128 | 2016,5,6,9.5,15.7,23.0 129 | 2016,5,7,8.6,18.2,25.2 130 | 2016,5,8,13.0,19.7,25.0 131 | 2016,5,9,14.1,19.7,23.9 132 | 2016,5,10,15.6,18.1,20.9 133 | 2016,5,11,14.1,19.7,24.7 134 | 2016,5,12,14.4,19.9,24.8 135 | 2016,5,13,8.6,14.4,21.5 136 | 2016,5,14,6.7,8.8,11.8 137 | 2016,5,15,5.4,8.5,11.7 138 | 2016,5,16,5.9,9.0,12.3 139 | 2016,5,17,6.4,12.2,16.1 140 | 2016,5,18,8.9,12.9,17.8 141 | 2016,5,19,10.0,12.6,16.8 142 | 2016,5,20,11.1,13.6,16.8 143 | 2016,5,21,11.1,16.9,22.5 144 | 2016,5,22,11.7,13.9,17.3 145 | 2016,5,23,10.4,11.7,13.5 146 | 2016,5,24,9.8,10.9,13.4 147 | 2016,5,25,7.3,11.4,15.1 148 | 2016,5,26,5.1,12.3,17.3 149 | 2016,5,27,11.1,15.8,20.8 150 | 2016,5,28,10.4,16.8,20.9 151 | 2016,5,29,14.0,16.6,20.3 152 | 2016,5,30,13.1,13.7,14.7 153 | 2016,5,31,13.1,17.7,21.9 154 | 2016,6,1,13.0,15.7,19.4 155 | 2016,6,2,12.1,13.0,14.1 156 | 2016,6,3,12.2,13.7,15.7 157 | 2016,6,4,12.7,18.4,24.2 158 | 2016,6,5,11.0,17.2,22.1 159 | 2016,6,6,11.0,17.2,22.3 160 | 2016,6,7,13.6,19.6,25.6 161 | 2016,6,8,12.0,14.7,18.4 162 | 2016,6,9,9.0,13.6,16.5 163 | 2016,6,10,8.4,14.8,19.3 164 | 2016,6,11,12.5,15.4,19.8 165 | 2016,6,12,12.7,16.4,21.5 166 | 2016,6,13,14.4,15.2,17.3 167 | 2016,6,14,11.6,15.0,18.3 168 | 2016,6,15,9.6,14.6,18.7 169 | 2016,6,16,9.7,15.1,19.4 170 | 2016,6,17,12.2,15.4,18.8 171 | 2016,6,18,9.7,13.2,15.9 172 | 2016,6,19,11.7,15.5,19.5 173 | 2016,6,20,14.4,15.7,16.5 174 | 2016,6,21,11.5,15.7,19.3 175 | 2016,6,22,11.3,19.7,25.0 176 | 2016,6,23,17.9,20.5,26.7 177 | 2016,6,24,11.8,17.5,20.5 178 | 2016,6,25,9.7,14.6,18.5 179 | 2016,6,26,11.6,15.4,17.9 180 | 2016,6,27,11.0,15.1,17.8 181 | 2016,6,28,9.2,15.1,20.2 182 | 2016,6,29,13.5,15.8,19.8 183 | 2016,6,30,14.6,16.1,18.2 184 | -------------------------------------------------------------------------------- /code_4/MyDeck.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | try: 4 | input = raw_input 5 | except NameError: 6 | pass 7 | 8 | import random 9 | 10 | class MyDeckIterator(object): 11 | def __init__(self, deck): 12 | self.deck = deck 13 | self.i = 0 14 | 15 | def __iter__(self): 16 | return self 17 | 18 | def __next__(self): 19 | try: 20 | card = self.deck[self.i] 21 | self.i += 1 22 | return card 23 | except IndexError: 24 | raise StopIteration('No more card') 25 | def next(self): 26 | return self.__next__() 27 | 28 | class MyDeck(object): 29 | cards_count = 52 30 | 31 | # spade, heart, diamond, club 32 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 33 | suit_count = 13 34 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 35 | 36 | def __init__(self): 37 | # 0~12 are Spade A~K, 38 | # 13~25 are Heart A~K, 39 | # 26~38 are Diamond A~K, 40 | # 39~51 are Club A~K 41 | # True means not-drawed-yet 42 | li = list(range(MyDeck.cards_count)) 43 | random.shuffle(li) 44 | 45 | self.cards = tuple(li) 46 | 47 | def __getitem__(self, i): 48 | if 0 <= i < MyDeck.cards_count: 49 | card_n = self.cards[i] 50 | q, r = divmod(card_n, MyDeck.suit_count) 51 | 52 | card = MyDeck.suits[q] + ' ' + MyDeck.ranks[r] 53 | return card 54 | else: 55 | raise IndexError('Index out of range') 56 | 57 | def __iter__(self): 58 | return MyDeckIterator(self) 59 | 60 | def __len__(self): 61 | return len(self.cards) 62 | 63 | def __str__(self): 64 | return 'The deck remains %d cards.' % len(self.cards) 65 | 66 | 67 | #### 68 | 69 | if __name__ == '__main__': 70 | d1 = MyDeck() 71 | # for i in range(MyDeck.cards_count): 72 | # print(d1[i]) 73 | # print(len(d1)) 74 | # print(len(d1)) 75 | 76 | # for card in d1: 77 | # print(card) 78 | # input('Press Entery to continue...') 79 | # for card in d1: 80 | # print(card) 81 | # input('Press Entery to continue...') 82 | 83 | # ditr_1 = iter(d1) 84 | # ditr_2 = iter(d1) 85 | 86 | # print('-' * 20) 87 | # print('ditr_1 ' + next(ditr_1)) 88 | # print('ditr_1 ' + next(ditr_1)) 89 | # print(' ditr_2 ' + next(ditr_2)) 90 | # print('ditr_1 ' + next(ditr_1)) 91 | # print(' ditr_2 ' + next(ditr_2)) 92 | # print('ditr_1 ' + next(ditr_1)) 93 | # print('ditr_1 ' + next(ditr_1)) 94 | # print(' ditr_2 ' + next(ditr_2)) 95 | # print('ditr_1 ' + next(ditr_1)) 96 | # print(' ditr_2 ' + next(ditr_2)) 97 | # print('-' * 20) 98 | 99 | # input('Press Entery to stop') 100 | 101 | -------------------------------------------------------------------------------- /code_4/MyDeck_generator_expr.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import random 4 | 5 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 6 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 7 | 8 | deck = (suits[n//13] + ' ' + ranks[n%13] for n in random.sample(range(52), 52)) 9 | 10 | for _ in range(5): 11 | print(next(deck)) 12 | print('') 13 | 14 | #### 15 | 16 | deck = (('Spade', 'Heart', 'Diamond', 'Club')[n//13] + ' ' + 17 | ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')[n%13] 18 | for n in random.sample(range(52), 52)) 19 | 20 | for _ in range(5): 21 | print(next(deck)) 22 | -------------------------------------------------------------------------------- /code_4/MyDeck_gf.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | def deck_gf(): 5 | cards_count = 52 6 | suit_count = 13 7 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 8 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 9 | 10 | import random 11 | li = list(range(cards_count)) 12 | random.shuffle(li) 13 | cards = tuple(li) 14 | 15 | i = 0 16 | while i < cards_count: 17 | card_n = cards[i] 18 | i += 1 19 | q, r = divmod(card_n, suit_count) 20 | card = suits[q] + ' ' + ranks[r] 21 | yield card 22 | 23 | #### 24 | deck_g = deck_gf() 25 | print(next(deck_g)) 26 | print(next(deck_g)) 27 | print(next(deck_g)) 28 | print(next(deck_g)) 29 | print(next(deck_g)) 30 | 31 | print('') 32 | 33 | for i, card in enumerate(deck_gf()): 34 | print(i, card) 35 | #### 36 | 37 | -------------------------------------------------------------------------------- /code_4/ascii_format.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | for i in range(0x20, 0x7e+1): 5 | print('%2X %c ' % (i, chr(i)), end='') 6 | if (i-0x20+1) % 8 == 0: 7 | print() 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /code_4/co_acc.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def acc_gf(n): 5 | while True: 6 | y = yield n 7 | n += 1 if y is None else y 8 | 9 | acc_g = acc_gf(100) 10 | print(next(acc_g)) 11 | print(acc_g.send(3)) 12 | print(next(acc_g)) 13 | print(acc_g.send(5)) 14 | 15 | -------------------------------------------------------------------------------- /code_4/dec_memo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def dec_memo(func): 4 | cache = func.cache = {} 5 | def wrapper(*args, **kwargs): 6 | key = str(args) + str(kwargs) 7 | if key not in cache: 8 | cache[key] = func(*args, **kwargs) 9 | return cache[key] 10 | return wrapper 11 | 12 | @dec_memo 13 | def fib_r(n): 14 | if n == 0 or n == 1: 15 | return n 16 | else: 17 | return fib_r(n-1) + fib_r(n-2) 18 | 19 | def fib_r2(n): 20 | if n == 0 or n == 1: 21 | return n 22 | else: 23 | return fib_r2(n-1) + fib_r2(n-2) 24 | 25 | def dec_time(func): 26 | def wrapper(*args, **kwargs): 27 | import time 28 | t_start = time.clock() 29 | res = func(*args, **kwargs) 30 | t_end = time.clock() 31 | print(func.__name__, t_end-t_start) 32 | return res 33 | return wrapper 34 | @dec_time 35 | def foo1(): 36 | for i in range(6000): 37 | fib_r(i) 38 | @dec_time 39 | def foo2(): 40 | for i in range(33): 41 | fib_r2(i) 42 | 43 | foo1() 44 | foo2() 45 | -------------------------------------------------------------------------------- /code_4/dec_memo_limit.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | import pickle 5 | def dec_memo_limit(func, limit=None): 6 | if isinstance(func, int): # 若func是整數,代表容量限制 7 | def wrapper(f): 8 | return dec_memo_limit(f, func) # 再呼叫自己 9 | return wrapper 10 | 11 | d = {} 12 | li = [] 13 | def wrapper(*args, **kwargs): 14 | key = pickle.dumps((args, kwargs)) 15 | try: 16 | li.append(li.pop(li.index(key))) 17 | except ValueError: 18 | d[key] = func(*args, **kwargs) 19 | li.append(key) 20 | if limit is not None and len(li) > limit: 21 | del d[li.pop(0)] 22 | return d[key] 23 | 24 | wrapper._memoize_dict = d 25 | wrapper._memoize_list = li 26 | wrapper._memoize_limit = limit 27 | wrapper._memoize_origfunc = func 28 | wrapper.__name__ = func.__name__ 29 | return wrapper 30 | 31 | #### 32 | 33 | @dec_memo_limit(200) 34 | def fib_r(n): 35 | if n == 0 or n == 1: 36 | return n 37 | else: 38 | return fib_r(n-1) + fib_r(n-2) 39 | print(fib_r._memoize_limit) 40 | 41 | @dec_memo_limit(100) 42 | def fib_r2(n): 43 | if n == 0 or n == 1: 44 | return n 45 | else: 46 | return fib_r2(n-1) + fib_r2(n-2) 47 | print(fib_r2._memoize_limit) 48 | 49 | def dec_time(func): 50 | def wrapper(*args, **kwargs): 51 | import time 52 | t_start = time.clock() 53 | res = func(*args, **kwargs) 54 | t_end = time.clock() 55 | print(func.__name__, t_end-t_start) 56 | return res 57 | return wrapper 58 | 59 | @dec_time 60 | def foo1(): 61 | for i in range(1000): 62 | fib_r(i) 63 | @dec_time 64 | def foo2(): 65 | for i in range(1000): 66 | fib_r2(i) 67 | 68 | foo1() 69 | foo2() 70 | 71 | import functools 72 | @functools.lru_cache(maxsize=100) 73 | def fib_r3(n): 74 | if n == 0 or n == 1: 75 | return n 76 | else: 77 | return fib_r3(n-1) + fib_r3(n-2) 78 | 79 | @dec_time 80 | def foo3(): 81 | for i in range(1000): 82 | fib_r3(i) 83 | foo3() 84 | 85 | # @functools.lru_cache(maxsize=300) 86 | # def bar(li): 87 | # return sum(li) 88 | 89 | # print(bar([1,2,3])) 90 | # print(bar([22,22,22])) 91 | 92 | @dec_memo_limit 93 | def fib_r4(n): 94 | if n == 0 or n == 1: 95 | return n 96 | else: 97 | return fib_r4(n-1) + fib_r4(n-2) 98 | print(fib_r4) 99 | 100 | 101 | -------------------------------------------------------------------------------- /code_4/dec_natural.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def dec_natural(func): 4 | def wrapper(n): 5 | if type(n) == int and n >= 0: 6 | return func(n) 7 | else: 8 | raise TypeError('Argument is not a natural number') 9 | 10 | return wrapper 11 | 12 | 13 | @dec_natural 14 | def fact_i(n): 15 | result = 1 16 | for i in range(1, n+1): 17 | result *= i 18 | return result 19 | 20 | print(fact_i(5)) 21 | print(fact_i(-1)) 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /code_4/dec_time.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def dec_time(func): 4 | def wrapper(*args, **kwargs): 5 | import time 6 | t_start = time.clock() 7 | res = func(*args, **kwargs) 8 | t_end = time.clock() 9 | print(func.__name__, t_end-t_start) 10 | return res 11 | return wrapper 12 | 13 | #### 14 | 15 | def fib_i(n): 16 | a, b = 0, 1 17 | for i in range(n): 18 | a, b = b, a+b 19 | return a 20 | 21 | def fib_memo(): 22 | memo = {0: 0, 1: 1} 23 | def sub(n): 24 | if n not in memo: 25 | memo[n] = sub(n-1) + sub(n-2) 26 | return memo[n] 27 | return sub 28 | fib_m = fib_memo() 29 | 30 | #### 31 | @dec_time 32 | def fib_i_test(n): 33 | for i in range(n): 34 | fib_i(i) 35 | 36 | @dec_time 37 | def fib_m_test(n): 38 | for i in range(n): 39 | fib_m(i) 40 | 41 | fib_i_test(5000) 42 | fib_m_test(5000) 43 | 44 | -------------------------------------------------------------------------------- /code_4/earthquake.py: -------------------------------------------------------------------------------- 1 | 2 | # _*_ coding: utf-8 _*_ 3 | 4 | import json, datetime 5 | 6 | 7 | with open('earthquake_data.json', 'r') as fin: 8 | data = json.load(fin) 9 | 10 | for item in data['features']: 11 | print("地點:{}".format(item['properties']['place'])) 12 | print("震度:{}".format(item['properties']['mag'])) 13 | 14 | # POSIX timestamp, in milliseconds 15 | ts = float(item['properties']['time']) / 1000.0 16 | t = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 17 | print("時間:{}".format(t)) 18 | 19 | print('-' * 20) 20 | 21 | #### 22 | 23 | with open('earthquake_data.json', 'r') as fin: 24 | with open('earthquake_data_new.json', 'w', encoding='utf-8') as fout: 25 | data = json.load(fin) 26 | 27 | data_new = [] 28 | 29 | for item in data['features']: 30 | loc = "地點:{}".format(item['properties']['place']) 31 | mag = "震度:{}".format(item['properties']['mag']) 32 | 33 | # POSIX timestamp, in milliseconds 34 | ts = float(item['properties']['time']) / 1000.0 35 | t = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 36 | tim = "時間:{}".format(t) 37 | 38 | data_new.append((tim, loc, mag)) 39 | 40 | json.dump(data_new, fout) 41 | 42 | #### 43 | 44 | # with open('earthquake_data_new.json', 'r', encoding='utf-8') as fin: 45 | # data = json.load(fin) 46 | # for item in data: 47 | # print(item) 48 | -------------------------------------------------------------------------------- /code_4/earthquake.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/earthquake.txt -------------------------------------------------------------------------------- /code_4/earthquake_data_small.json: -------------------------------------------------------------------------------- 1 | {"type":"FeatureCollection", 2 | "metadata":{ 3 | "generated":1467612588000, 4 | "url":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson", 5 | "title":"USGS All Earthquakes, Past Hour", 6 | "status":200, 7 | "api":"1.5.2", 8 | "count":2}, 9 | "features":[ 10 | {"type":"Feature", 11 | "properties":{ 12 | "mag":2.01, 13 | "place":"17km ESE of Mammoth Lakes, California", 14 | "time":1467611067950, 15 | "updated":1467612242509, 16 | "tz":-420, 17 | "url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72658291", 18 | "detail":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/nc72658291.geojson", 19 | "felt":null, 20 | "cdi":null, 21 | "mmi":null, 22 | "alert":null, 23 | "status":"automatic", 24 | "tsunami":0, 25 | "sig":62, 26 | "net":"nc", 27 | "code":"72658291", 28 | "ids":",nc72658291,", 29 | "sources":",nc,", 30 | "types":",general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,", 31 | "nst":24, 32 | "dmin":0.0344, 33 | "rms":0.04, 34 | "gap":97, 35 | "magType":"md", 36 | "type":"earthquake", 37 | "title":"M 2.0 - 17km ESE of Mammoth Lakes, California"}, 38 | "geometry":{"type":"Point", 39 | "coordinates":[-118.7868347,37.5974998,4.93]}, 40 | "id":"nc72658291"}, 41 | 42 | {"type":"Feature","properties":{"mag":1.12,"place":"8km S of Idyllwild, CA","time":1467609687070,"updated":1467610362520,"tz":-420,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/ci37620208","detail":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ci37620208.geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"automatic","tsunami":0,"sig":19,"net":"ci","code":"37620208","ids":",ci37620208,","sources":",ci,","types":",focal-mechanism,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,","nst":47,"dmin":0.04459,"rms":0.19,"gap":28,"magType":"ml","type":"earthquake","title":"M 1.1 - 8km S of Idyllwild, CA"},"geometry":{"type":"Point","coordinates":[-116.7165,33.6665,14.58]},"id":"ci37620208"}],"bbox":[-118.7868347,33.6665,4.93,-116.7165,37.5974998,14.58]} 43 | 44 | -------------------------------------------------------------------------------- /code_4/earthquake_data_small_b.json: -------------------------------------------------------------------------------- 1 | { 2 | "type":"FeatureCollection", 3 | "metadata":{ 4 | "generated":1467612588000, 5 | "url":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson", 6 | "title":"USGS All Earthquakes, Past Hour", 7 | "status":200, 8 | "api":"1.5.2", 9 | "count":2 10 | }, 11 | "features":[ 12 | { 13 | "type":"Feature", 14 | "properties":{ 15 | "mag":2.01, 16 | "place":"17km ESE of Mammoth Lakes, California", 17 | "time":1467611067950, 18 | "updated":1467612242509, 19 | "tz":-420, 20 | "url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72658291", 21 | "detail":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/nc72658291.geojson", 22 | "felt":null, 23 | "cdi":null, 24 | "mmi":null, 25 | "alert":null, 26 | "status":"automatic", 27 | "tsunami":0, 28 | "sig":62, 29 | "net":"nc", 30 | "code":"72658291", 31 | "ids":",nc72658291,", 32 | "sources":",nc,", 33 | "types":",general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,", 34 | "nst":24, 35 | "dmin":0.0344, 36 | "rms":0.04, 37 | "gap":97, 38 | "magType":"md", 39 | "type":"earthquake", 40 | "title":"M 2.0 - 17km ESE of Mammoth Lakes, California" 41 | }, 42 | "geometry":{ 43 | "type":"Point", 44 | "coordinates":[ 45 | -118.7868347, 46 | 37.5974998, 47 | 4.93 48 | ] 49 | }, 50 | "id":"nc72658291" 51 | }, 52 | { 53 | "type":"Feature", 54 | "properties":{ 55 | "mag":1.12, 56 | "place":"8km S of Idyllwild, CA", 57 | "time":1467609687070, 58 | "updated":1467610362520, 59 | "tz":-420, 60 | "url":"http://earthquake.usgs.gov/earthquakes/eventpage/ci37620208", 61 | "detail":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ci37620208.geojson", 62 | "felt":null, 63 | "cdi":null, 64 | "mmi":null, 65 | "alert":null, 66 | "status":"automatic", 67 | "tsunami":0, 68 | "sig":19, 69 | "net":"ci", 70 | "code":"37620208", 71 | "ids":",ci37620208,", 72 | "sources":",ci,", 73 | "types":",focal-mechanism,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,", 74 | "nst":47, 75 | "dmin":0.04459, 76 | "rms":0.19, 77 | "gap":28, 78 | "magType":"ml", 79 | "type":"earthquake", 80 | "title":"M 1.1 - 8km S of Idyllwild, CA" 81 | }, 82 | "geometry":{ 83 | "type":"Point", 84 | "coordinates":[ 85 | -116.7165, 86 | 33.6665, 87 | 14.58 88 | ] 89 | }, 90 | "id":"ci37620208" 91 | } 92 | ], 93 | "bbox":[ 94 | -118.7868347, 95 | 33.6665, 96 | 4.93, 97 | -116.7165, 98 | 37.5974998, 99 | 14.58 100 | ] 101 | } -------------------------------------------------------------------------------- /code_4/fact.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def fact_i(n): 4 | result = 1 5 | for i in range(1, n+1): 6 | result *= i 7 | return result 8 | #### 9 | def fact_r(n): 10 | if n == 1 or n == 0: 11 | return 1 12 | else: 13 | return n * fact_r(n-1) 14 | #### 15 | def fact_r2(n, answer=1): 16 | if n == 1 or n == 0: 17 | return answer 18 | else: 19 | return fact_r2(n-1, n*answer) 20 | #### 21 | 22 | if __name__ == '__main__': 23 | for n in range(10): 24 | fi = fact_i(n) 25 | fr = fact_r(n) 26 | fr2 = fact_r2(n) 27 | if fi != fr: 28 | print('error: %d, %d, %d' % (n, fi, fr)) 29 | if fi != fr2: 30 | print('error: %d, %d, %d' % (n, fi, fr2)) 31 | 32 | -------------------------------------------------------------------------------- /code_4/fib.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def fib_r(n): 4 | if n == 0 or n == 1: 5 | return n 6 | else: 7 | return fib_r(n-1) + fib_r(n-2) 8 | 9 | def fib_r2(n): 10 | return n if n==0 or n==1 else fib_r(n-1) + fib_r(n-2) 11 | #### 12 | def fib_i(n): 13 | a, b = 0, 1 14 | for i in range(n): 15 | a, b = b, a+b 16 | return a 17 | #### 18 | memo = {0: 0, 1: 1} 19 | def fib_m(n): 20 | if n not in memo: 21 | memo[n] = fib_m(n-1) + fib_m(n-2) 22 | return memo[n] 23 | 24 | #### 25 | def fib_memo(): 26 | memo = {0: 0, 1: 1} 27 | def sub(n): 28 | if n not in memo: 29 | memo[n] = sub(n-1) + sub(n-2) 30 | return memo[n] 31 | return sub 32 | fib_m = fib_memo() 33 | 34 | #### 35 | for x in range(20): 36 | fr = fib_r(x) 37 | fi = fib_i(x) 38 | fm = fib_m(x) 39 | fr2 = fib_r2(x) 40 | 41 | if fr != fi or fi != fm or fi != fr2: 42 | print('error: fib(%d) %d %d %d' % (x, fr, fi, fm)) 43 | 44 | 45 | -------------------------------------------------------------------------------- /code_4/file_bad.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import print_function 5 | from io import open 6 | 7 | f1 = 'file_basic.txt' 8 | f2 = 'file_basic_utf8.txt' 9 | f3 = 'file_basic_big5_cp950.txt' 10 | 11 | with open('file_basic.txt', 'r', encoding='utf-8') as fin: 12 | for line in fin.readlines(): 13 | print(line, end='') 14 | 15 | 16 | with open('file_basic.txt', 'r', encoding='utf-8') as fin: 17 | line = fin.readline() 18 | while line: 19 | print(line, end='') 20 | line = fin.readline() 21 | -------------------------------------------------------------------------------- /code_4/file_basic.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import print_function 5 | from io import open 6 | 7 | f1 = 'file_basic.txt' 8 | f2 = 'file_basic_utf8.txt' 9 | f3 = 'file_basic_big5_cp950.txt' 10 | 11 | fin = open(f1, 'r') 12 | # fin = open(f3, 'r', encoding='big5') # ascii big5 cp950 utf-8 13 | 14 | for line in fin: 15 | print(line, end='') 16 | 17 | fin.close() 18 | 19 | #### 20 | 21 | # print() 22 | 23 | # with open('file_basic.txt', 'r') as fin: 24 | # for line in fin: 25 | # print(line, end='') 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /code_4/file_basic.txt: -------------------------------------------------------------------------------- 1 | abc 2 | 3 | def 123 4 | 5 | +-*/ how are you? 6 | bye 7 | -------------------------------------------------------------------------------- /code_4/file_basic_big5_cp950.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/file_basic_big5_cp950.txt -------------------------------------------------------------------------------- /code_4/file_basic_removed.txt: -------------------------------------------------------------------------------- 1 | abc 2 | def 123 3 | +-*/ how are you? 4 | bye 5 | -------------------------------------------------------------------------------- /code_4/file_basic_utf8.txt: -------------------------------------------------------------------------------- 1 | abc 你好 2 | 3 | 4 | def 123 天氣 5 | 6 | 7 | +-*/ how are you? 8 | bye 9 | -------------------------------------------------------------------------------- /code_4/file_remove_blankline.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import print_function 5 | from io import open 6 | 7 | f1 = 'file_basic.txt' 8 | f2 = 'file_basic_utf8.txt' 9 | f3 = 'file_basic_big5_cp950.txt' 10 | 11 | fin = open(f1, 'r') 12 | # fin = open(f3, 'r', encoding='big5') # ascii big5 cp950 utf-8 13 | 14 | fout = open(f1[:-4] + '_removed.txt', 'w') 15 | 16 | for line in fin: 17 | s = line.strip() 18 | if s: 19 | fout.write(line) 20 | 21 | fin.close() 22 | fout.close() 23 | 24 | #### 25 | 26 | # print() 27 | 28 | # with open(f1, 'r') as fin: 29 | # with open(f1[:-4] + '_removed.txt', 'w') as fout: 30 | # for line in fin: 31 | # s = line.strip() 32 | # if s: 33 | # fout.write(line) 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /code_4/fl_ctof.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | tc = (0, 100, 30.2, 22.5, -15.8, 23.7) 5 | 6 | def ctof(c): # 攝氏轉華氏 7 | return c * 9.0 / 5.0 + 32 8 | 9 | itr_f = map(ctof, tc) 10 | 11 | for f in itr_f: 12 | print(f) 13 | 14 | #### 改用lambda 15 | print('') 16 | for f in map(lambda c: c*9.0/5.0+32, tc): 17 | print(f) 18 | 19 | #### zip原攝氏溫度與華氏溫度 20 | print('') 21 | for c, f in zip(tc, map(ctof, tc)): 22 | print(c, f) 23 | 24 | #### 運用產生器,自己寫map(功能較少) 25 | def my_map(func, itb): 26 | for e in itb: 27 | yield func(e) 28 | 29 | print('') 30 | for f in my_map(ctof, tc): 31 | print(f) 32 | 33 | -------------------------------------------------------------------------------- /code_4/fl_fact.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from functools import reduce 4 | 5 | # def mul(x, y): return x * y 6 | 7 | from operator import mul 8 | 9 | def fact(n): 10 | return reduce(mul, range(1, n+1), 1) 11 | 12 | 13 | -------------------------------------------------------------------------------- /code_4/fl_failed.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/fl_failed.py -------------------------------------------------------------------------------- /code_4/fl_odd_fibs.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/fl_odd_fibs.py -------------------------------------------------------------------------------- /code_4/fl_sq_even.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/fl_sq_even.py -------------------------------------------------------------------------------- /code_4/fl_tph.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Problem 45: Triangular, pentagonal, and hexagonal 4 | # https://projecteuler.net/problem=45 5 | 6 | from itertools import count 7 | # from itertools import imap as map # 2.x 8 | 9 | def tn(n): return n * (n+1) // 2 10 | def pn(n): return n * (3*n - 1) // 2 11 | def hn(n): return n * (2*n - 1) 12 | 13 | def filter_equal(ita, itb): 14 | a = next(ita) 15 | b = next(itb) 16 | while True: 17 | if a < b: 18 | a = next(ita) 19 | elif a > b: 20 | b = next(itb) 21 | else: 22 | yield a 23 | a = next(ita) 24 | 25 | def tph_gf(): 26 | while True: 27 | yield from filter_equal(map(hn, count(1)), 28 | filter_equal(map(tn, count(1)), 29 | map(pn, count(1)))) 30 | 31 | tph = tph_gf() 32 | print(next(tph)) # 1 33 | print(next(tph)) # 40755 34 | print(next(tph)) # 1533776805 35 | -------------------------------------------------------------------------------- /code_4/frange_class.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | class Frange(): 5 | def __init__(self, start, end=None, inc=None): 6 | self.start = float(start) # 避免某些情況出現int 7 | self.end = end 8 | self.inc = inc 9 | 10 | if self.end is None: # 傳入一個參數的情況 11 | self.end = self.start 12 | self.start = 0.0 13 | 14 | if self.inc is None: 15 | self.inc = 1.0 16 | 17 | def __iter__(self): # 既是Iterable、也是Iterator 18 | return self 19 | 20 | def __next__(self): 21 | x = self.start 22 | self.start += self.inc 23 | 24 | if abs(x) < abs(self.end): # 處理正、負的情況 25 | return x 26 | else: 27 | raise StopIteration 28 | 29 | #### 30 | 31 | for x in Frange(3): 32 | print(x) 33 | print() 34 | print(list(Frange(2.55, 3.7, 0.1))) 35 | print() 36 | print(list(Frange(0, 1, 0.1))) 37 | 38 | -------------------------------------------------------------------------------- /code_4/frange_gf.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | def frange(start, end=None, inc=None): 5 | start = float(start) 6 | 7 | if end is None: 8 | end = start 9 | start = 0.0 10 | 11 | if inc is None: 12 | inc = 1.0 13 | 14 | while abs(start) < abs(end): 15 | yield start 16 | start += inc 17 | 18 | #### 19 | 20 | 21 | for x in frange(3): 22 | print(x) 23 | print() 24 | print(list(frange(2.55, 3.7, 0.1))) 25 | print() 26 | print(list(frange(0, 1, 0.1))) 27 | 28 | -------------------------------------------------------------------------------- /code_4/hello_ascii.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # print hello 4 | print('hello') 5 | 6 | -------------------------------------------------------------------------------- /code_4/hello_big5_cp950.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/hello_big5_cp950.py -------------------------------------------------------------------------------- /code_4/hello_big5_cp950_shebang.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/hello_big5_cp950_shebang.py -------------------------------------------------------------------------------- /code_4/hello_utf8.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # print 哈囉 4 | print('哈囉') 5 | 6 | # print(u'哈囉') # 2.x 7 | 8 | -------------------------------------------------------------------------------- /code_4/hello_utf8_shebang.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | # print 哈囉 5 | print('哈囉') 6 | # print(u'哈囉') # 2.x 7 | 8 | -------------------------------------------------------------------------------- /code_4/hex.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import print_function 5 | from io import open 6 | import sys 7 | 8 | HEX = 16 9 | template = '%02X ' * HEX 10 | template_head = ' ' + template 11 | # template_line = '%02X ' + template 12 | 13 | def hex_show(filename, max=None): 14 | with open(filename, 'rb') as fin: 15 | print(template_head % tuple(range(HEX))) 16 | print() 17 | 18 | data = fin.read(HEX) 19 | len_total = 0 20 | while len(data): 21 | len_total += len(data) 22 | if max and len_total > max: 23 | break 24 | 25 | head = (len_total // HEX - (1 if len_total % HEX == 0 else 0)) * HEX 26 | print('%04X ' % head, end='') 27 | for b in data: 28 | print('%02X ' % b, end='') 29 | print() 30 | 31 | data = fin.read(HEX) 32 | 33 | if len(sys.argv) == 2: 34 | hex_show(sys.argv[1], HEX*8) 35 | elif len(sys.argv) == 3: 36 | hex_show(sys.argv[1], None if int(sys.argv[2]) <= 0 else int(sys.argv[2])) 37 | else: 38 | print('Usage: hex.py ') 39 | 40 | 41 | -------------------------------------------------------------------------------- /code_4/hf_sum.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def sum_number(start, end): 4 | result = 0 5 | while start <= end: 6 | result += start 7 | start += 1 8 | return result 9 | 10 | def sum_square(start, end): 11 | result = 0 12 | while start <= end: 13 | result += start**2 14 | start += 1 15 | return result 16 | 17 | # pi/8 18 | def sum_pi(start, end): 19 | result = 0 20 | while start <= end: 21 | result += 1.0 / (start * (start+2)) 22 | start += 4 23 | return result 24 | 25 | def sum_hf(item, start, next, end): 26 | result = 0 27 | while start <= end: 28 | result += item(start) 29 | start = next(start) 30 | return result 31 | 32 | #### 33 | def sum_number_r(start, end): 34 | if start > end: 35 | return 0 36 | else: 37 | return start + sum_number_r(start+1, end) 38 | def sum_square_r(start, end): 39 | if start > end: 40 | return 0 41 | else: 42 | return start**2 + sum_square_r(start+1, end) 43 | def sum_pi_r(start, end): 44 | if start > end: 45 | return 0 46 | else: 47 | return (1.0 / (start * (start+2))) + sum_pi_r(start+4, end) 48 | 49 | def sum_hf_r(item, start, next, end): 50 | if start > end: 51 | return 0 52 | else: 53 | return item(start) + sum_hf_r(item, next(start), next, end) 54 | 55 | #### 56 | 57 | 58 | #### 59 | if __name__ == '__main__': 60 | tests = [(0, 10), (100, 200), (2000, 2500)] 61 | for t in tests: 62 | fa = sum(range(t[0], t[1]+1)) 63 | fb = sum_number(t[0], t[1]) 64 | fc = sum_hf(lambda x: x, t[0], lambda i: i+1, t[1]) 65 | fd = sum_number_r(t[0], t[1]) 66 | fe = sum_hf_r(lambda x: x, t[0], lambda i: i+1, t[1]) 67 | if fa == fb == fc == fd == fe: 68 | print('pass') 69 | for t in tests: 70 | fa = sum([x**2 for x in range(t[0], t[1]+1)]) 71 | fb = sum_square(t[0], t[1]) 72 | fc = sum_hf(lambda x: x**2, t[0], lambda i: i+1, t[1]) 73 | fd = sum_square_r(t[0], t[1]) 74 | fe = sum_hf_r(lambda x: x**2, t[0], lambda i: i+1, t[1]) 75 | if fa == fb == fc == fd == fe: 76 | print('pass') 77 | for end in range(200, 205): 78 | print(sum_pi(1, end) * 8) 79 | print(sum_pi_r(1, end) * 8) 80 | print(sum_hf(lambda x: 1.0 / (x * (x+2)), 1, lambda i: i+4, end) * 8) 81 | print(sum_hf_r(lambda x: 1.0 / (x * (x+2)), 1, lambda i: i+4, end) * 8) 82 | print('---') 83 | 84 | 85 | -------------------------------------------------------------------------------- /code_4/knmi.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import print_function 5 | from io import open 6 | import csv 7 | import time 8 | 9 | filename = 'KNMI_20160101_20160630.txt' 10 | 11 | with open(filename, 'r', encoding='utf-8') as fin: 12 | print('YYYY/MM/DD %5s %5s %5s' % ('Min', 'MAX', 'AVG')) 13 | print('-' * 29) 14 | for line in fin: 15 | if line.strip()[0] == '#': 16 | continue 17 | 18 | site, date, tavg, tmin, tmax = line.split(',') 19 | 20 | date = date.strip() 21 | year = int(date[:4]) 22 | month = int(date[4:4+2]) 23 | day = int(date[6:]) 24 | 25 | tavg = float(tavg.strip()) * 0.1 26 | tmin = float(tmin.strip()) * 0.1 27 | tmax = float(tmax.strip()) * 0.1 28 | 29 | print('%4d/%2d/%2d %5.1f % 5.1f % 5.1f' % (year, month, day, tmin, tmax, tavg)) 30 | 31 | 32 | #### csv 33 | 34 | with open(filename, 'r', encoding='utf-8') as fin: 35 | with open(filename[:-4] + '_new.csv', 'w', encoding='utf-8') as fout: 36 | csvreader = csv.reader(fin, delimiter=',') 37 | 38 | csvwriter = csv.writer(fout, delimiter=',') 39 | csvwriter.writerow(('YYYY', 'MM', 'DD', 'Min', 'MAX', 'AVG')) 40 | 41 | for rows in csvreader: 42 | if rows[0].strip()[0] == '#': 43 | continue 44 | 45 | site, date, tavg, tmin, tmax = rows 46 | 47 | ymd = time.strptime(date, '%Y%m%d') # struct_time 48 | year = ymd.tm_year 49 | month = ymd.tm_mon 50 | day = ymd.tm_mday 51 | 52 | tavg = format(float(tavg.strip()) * 0.1, '.1f') 53 | tmin = format(float(tmin.strip()) * 0.1, '.1f') 54 | tmax = format(float(tmax.strip()) * 0.1, '.1f') 55 | 56 | csvwriter.writerow((year, month, day, tmin, tavg, tmax)) 57 | 58 | -------------------------------------------------------------------------------- /code_4/lex_perm.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Problem 24: Lexicographic permutations 4 | # https://projecteuler.net/problem=24 5 | 6 | # 7 | def perm_gf(s): 8 | if len(s) == 1: 9 | yield s[0] 10 | else: 11 | for i, c in enumerate(s): 12 | stmp = s[:i] + s[i+1:] 13 | for sub in perm_gf(stmp): 14 | yield c + sub 15 | 16 | # for i, x in enumerate(perm_gf('0123456789')): 17 | # if i < 4: 18 | # print(x) 19 | 20 | def lp_perm(s, nth): 21 | for i, x in enumerate(perm_gf(s)): 22 | if i == nth: 23 | return x 24 | 25 | #### 26 | def factorial(n): 27 | result = 1 28 | for i in range(1, n+1): 29 | result *= i 30 | return result 31 | 32 | def lp(s, nth): 33 | if nth == 0: 34 | return s 35 | else: 36 | seg = factorial(len(s) - 1) 37 | idx = nth // seg 38 | c = s[idx] 39 | stmp = s[:idx] + s[idx+1:] 40 | return c + lp(stmp, nth - idx*seg) 41 | 42 | # 43 | def test(): 44 | if (list(perm_gf('012')) == ['012', '021', '102', '120', '201', '210'] and 45 | lp('012', 5 - 1) == '201' and 46 | lp('0123456789', 10**6 - 1) == lp_perm('0123456789', 10**6 - 1)): 47 | return 'Pass' 48 | else: 49 | return 'Fail' 50 | 51 | def main(): 52 | return lp('0123456789', 10**6 - 1) 53 | 54 | if __name__ == '__main__': 55 | import sys 56 | if len(sys.argv) >= 2 and sys.argv[1] == 'test': 57 | print(test()) 58 | else: 59 | print(main()) 60 | 61 | -------------------------------------------------------------------------------- /code_4/local_bar.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | y = 100 5 | 6 | def bar(x): 7 | print(y) 8 | y = x + 10 9 | return y 10 | 11 | bar(3) 12 | -------------------------------------------------------------------------------- /code_4/local_foo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | x = 3 5 | 6 | def foo(): 7 | x += 10 8 | print(x) 9 | 10 | foo() 11 | print(x) 12 | -------------------------------------------------------------------------------- /code_4/m99_format.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | for y in range(1, 9+1): 4 | for x in (2, 3, 4, 5): 5 | print('%2d x%2d = %2d ' % (x, y, x*y), end='') 6 | print() 7 | 8 | print() 9 | 10 | for y in range(1, 9+1): 11 | for x in (6, 7, 8, 9): 12 | print('%2d x%2d = %2d ' % (x, y, x*y), end='') 13 | print() 14 | 15 | 16 | # def p99(li): 17 | # for y in range(1, 9+1): 18 | # result = [] 19 | # for x in li: 20 | # s = '%2d x%2d = %2d' % (x, y, x*y) 21 | # result.append(s) 22 | # print(' '.join(result)) 23 | 24 | # p99([2, 3, 4, 5]) 25 | # print('') 26 | # p99([6, 7, 8, 9]) 27 | 28 | -------------------------------------------------------------------------------- /code_4/max_so_far.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def max_so_far(m=0): 5 | def sub(x=m, *t): 6 | nonlocal m # 3.x 7 | x = max(t, default=x) 8 | if x > m: 9 | m = x 10 | return m 11 | return sub 12 | 13 | msf = max_so_far() 14 | print(msf(3)) 15 | print(msf(5)) 16 | print(msf(-1)) 17 | print(msf(6)) 18 | print(msf(33)) 19 | print(msf(11)) 20 | print(msf(67)) 21 | print(msf(-1)) 22 | -------------------------------------------------------------------------------- /code_4/perm.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | from itertools import permutations 4 | p = permutations 5 | 6 | def perm(iterable, r=None): 7 | items = tuple(iterable) # 欲排列的東西 8 | r = len(items) if r is None else r 9 | 10 | answers = [] # 存放結果的串列 11 | 12 | def sub(items, k, p): # 從items裡取出k個,p是目前已有的排列 13 | if k == 0: 14 | answers.append(p) 15 | else: 16 | for i in range(len(items)): 17 | # 遞迴呼叫,去掉索引i的元素 18 | sub(items[:i] + items[i+1:], k-1, p+(items[i],)) 19 | sub(items, r, ()) 20 | 21 | return answers 22 | 23 | #### 24 | 25 | def perm_gf(iterable, r=None, p=()): 26 | items = tuple(iterable) 27 | n = len(items) 28 | r = n if r is None else r 29 | 30 | if r == 0: 31 | yield p 32 | else: 33 | for i in range(n): 34 | yield from perm_gf(items[:i] + items[i+1:], r-1, p+(items[i],)) 35 | # for perm in perm_gf(items[:i] + items[i+1:], r-1, p+(items[i],)): 36 | # yield perm 37 | 38 | #### 39 | if __name__ == '__main__': 40 | tests = (list(range(3)), ['a','b','c','d'], list(range(100, 106))) 41 | for t in tests: 42 | pa = list(p(t)) 43 | pb = perm(t) 44 | pc = tuple(perm_gf(t)) 45 | if set(pa) == set(pb) == set(pc): 46 | print('yes') 47 | else: 48 | print('no') 49 | for t in tests: 50 | for r in range(1, len(t)): 51 | pa = list(p(t, r)) 52 | pb = perm(t, r) 53 | pc = tuple(perm_gf(t, r)) 54 | if set(pa) == set(pb) == set(pc): 55 | print('yes') 56 | else: 57 | print('no') 58 | -------------------------------------------------------------------------------- /code_4/perm_product.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | from itertools import permutations 4 | p = permutations 5 | 6 | def perm(iterable, r=None): 7 | items = tuple(iterable) # 欲排列的東西 8 | r = len(items) if r is None else r 9 | 10 | answers = [] # 存放結果的串列 11 | 12 | def sub(items, k, p): # 從items裡取出k個,p是目前已有的排列 13 | if k == 0: 14 | answers.append(p) 15 | else: 16 | for i in range(len(items)): 17 | # 遞迴呼叫,去掉索引i的元素 18 | sub(items[:i] + items[i+1:], k-1, p+(items[i],)) 19 | sub(items, r, ()) 20 | 21 | return answers 22 | 23 | #### 24 | from itertools import product 25 | 26 | # print(tuple(product(range(3), repeat=3))) 27 | 28 | def perm_product(iterable, r=None): 29 | items = tuple(iterable) 30 | n = len(items) 31 | r = n if r is None else r 32 | 33 | answers = [] 34 | 35 | for indices in product(range(n), repeat=r): 36 | if len(set(indices)) == r: 37 | answers.append(tuple(items[i] for i in indices)) 38 | 39 | return answers 40 | 41 | #### 42 | 43 | def perm_product_gf(iterable, r=None): 44 | items = tuple(iterable) 45 | n = len(items) 46 | r = n if r is None else r 47 | 48 | for indices in product(range(n), repeat=r): 49 | if len(set(indices)) == r: 50 | yield tuple(items[i] for i in indices) 51 | 52 | #### 53 | if __name__ == '__main__': 54 | tests = (list(range(3)), ['a','b','c','d'], list(range(100, 106))) 55 | for t in tests: 56 | pa = list(p(t)) 57 | pb = perm(t) 58 | pc = perm_product(t) 59 | pd = tuple(perm_product_gf(t)) 60 | if set(pa) == set(pb) == set(pc) == set(pd): 61 | print('yes') 62 | else: 63 | print('no') 64 | for t in tests: 65 | for r in range(1, len(t)): 66 | pa = list(p(t, r)) 67 | pb = perm(t, r) 68 | pc = perm_product(t, r) 69 | pd = tuple(perm_product_gf(t, r)) 70 | if set(pa) == set(pb) == set(pc) == set(pd): 71 | print('yes') 72 | else: 73 | print('no') 74 | -------------------------------------------------------------------------------- /code_4/pickle_rw.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import print_function 5 | from io import open 6 | import pickle 7 | 8 | data = {'a': [1, 2, 3, 4], 9 | 'John': 'abcdef', 10 | 334455: 778899, 11 | 'default': None} 12 | 13 | with open('pickle_rw.bin', 'wb') as fout: 14 | pickle.dump(data, fout) 15 | 16 | with open('pickle_rw.bin', 'rb') as fin: 17 | d = pickle.load(fin) 18 | print(d['John']) 19 | print(d[334455]) 20 | 21 | 22 | -------------------------------------------------------------------------------- /code_4/queen_basic.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | def queen(n): 4 | answers = [] 5 | 6 | # 已有部分擺法ans,判斷是否可在下一列的第col欄擺上皇后 7 | def is_safe(ans, col): 8 | for i, c in enumerate(ans): 9 | if len(ans)-i == abs(c-col): 10 | return False 11 | return True 12 | 13 | # def is_safe(ans, col): 14 | # return all([not len(ans)-i == abs(c-col) 15 | # for i, c in enumerate(ans)]) 16 | 17 | # 遞迴 18 | def sub(ans): 19 | if len(ans) == n: # 已擺入n個皇后 20 | answers.append(ans) 21 | else: 22 | for col in range(n): # 逐一判斷要把皇后擺在次列的第0~(n-1)欄 23 | if col not in ans and is_safe(ans, col): 24 | sub(ans + (col,)) # 若可以,加入答案,繼續下次遞迴 25 | 26 | sub(()) # 一開始ans是()空tuple,什麼都還沒擺 27 | return answers 28 | 29 | #### 30 | def is_safe(ans, col): 31 | for i, c in enumerate(ans): 32 | if len(ans)-i == abs(c-col): 33 | return False 34 | return True 35 | 36 | def queen_gf(n, ans=()): 37 | 38 | if len(ans) == n: 39 | yield ans 40 | else: 41 | for col in range(n): 42 | if col not in ans and is_safe(ans, col): 43 | yield from queen_gf(n, (ans + (col,))) 44 | 45 | #### 46 | if __name__ == '__main__': 47 | n = 8 48 | answers = queen(n) 49 | for ans in answers: 50 | print(ans) 51 | print(len(answers)) 52 | print('-' * 20) 53 | answers2 = tuple(queen_gf(n)) 54 | if set(answers) == set(answers2): 55 | print('yes') 56 | else: 57 | print('no') 58 | print(len(answers2)) 59 | 60 | -------------------------------------------------------------------------------- /code_4/queen_c++.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/queen_c++.cpp -------------------------------------------------------------------------------- /code_4/queen_hettingers.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | # Raymond Hettingers 4 | # http://code.activestate.com/recipes/576647/ 5 | from itertools import permutations 6 | 7 | def queen(n): 8 | answers = [] 9 | cols = range(n) 10 | 11 | # 產生出所有可能的擺法 12 | for ans in permutations(cols): # 逐一迭代,判斷擺法是否安全 13 | if (n == 14 | len(set([ans[i]+i for i in cols])) == 15 | len(set([ans[i]-i for i in cols]))): 16 | answers.append(ans) 17 | 18 | return answers 19 | 20 | -------------------------------------------------------------------------------- /code_4/queen_hettingers_gf.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Raymond Hettingers 4 | # http://code.activestate.com/recipes/576647/ 5 | from itertools import permutations 6 | 7 | def queen_gf(n): 8 | cols = range(n) 9 | for ans in permutations(cols): 10 | if (n == len(set(ans[i]+i for i in cols)) == 11 | len(set(ans[i]-i for i in cols))): 12 | yield ans 13 | -------------------------------------------------------------------------------- /code_4/queen_howell.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | # Steve Howell 4 | # http://wiki.python.org/moin/SimplePrograms 5 | 6 | def queen(n): 7 | answers = [()] # ()是空tuple,代表還沒擺上任一皇后 8 | 9 | # 已有擺法ans,想在下列的第col欄擺皇后,判斷會不會被攻擊 10 | def under_attack(col, ans): 11 | return (col in ans or 12 | any([len(ans)-i == abs(c-col) 13 | for i,c in enumerate(ans)])) 14 | 15 | for row in range(n): # n列 16 | answers = [ans + (col,) 17 | for ans in answers 18 | for col in range(n) # n欄 19 | if not under_attack(col, ans)] 20 | return answers 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /code_4/queen_test.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import queen_hettingers as het 4 | import queen_howell as how 5 | import queen_basic as ba 6 | import queen_hettingers_gf as het_gf 7 | 8 | n = 8 9 | 10 | het_answers = het.queen(n) 11 | print(len(het_answers)) 12 | print(het_answers) 13 | 14 | how_answers = how.queen(n) 15 | # for answer in answers: 16 | # print(list(enumerate(answer, start=1))) 17 | #print(answer) 18 | 19 | print(len(how_answers)) 20 | print(how_answers) 21 | 22 | ba_answers = ba.queen(n) 23 | print(len(ba_answers)) 24 | print(ba_answers) 25 | 26 | ba_gf_answers = tuple(ba.queen_gf(n)) 27 | 28 | queen_het_g = het_gf.queen_gf(n) 29 | het_g_answers = [x for x in queen_het_g] 30 | 31 | print('') 32 | 33 | #if set(iter(het_answers)) == set(iter(how_answers)): 34 | if (set(het_answers) == set(how_answers) == set(ba_answers) == set(het_g_answers) 35 | == set(ba_gf_answers)): 36 | print('---yes---') 37 | else: 38 | print('---no---') 39 | 40 | -------------------------------------------------------------------------------- /code_4/scope_basic.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | li = [0, 1, 2, 3, 4] # 第一次指派名稱li於全域範圍,指向串列物件 5 | a = 3 # 第一次指派名稱a,指向整數物件3 6 | a = len(li) # 名稱a、li位於全域範圍,在全域範圍內沒有名稱len, 7 | # 到內建範圍去找,找到了內建函式len 8 | 9 | b = sum(li) # 第一次指派名稱b,名稱sum位於內建範圍,li在全域 10 | 11 | def foo_1(a, b): # 第一次指派名稱foo_1,指向新建立的函式物件, 12 | d = a + b - c # 區域名稱a、b,掩蓋住全域名稱a與b。 13 | return d # d第一次指派。 14 | # c雖然目前看不到,但尚未執行函式體,所以不會出錯。 15 | 16 | def foo_2(a, b): # 第一次指派名稱foo_2,指向新建立的函式物件, 17 | def bar(x): # 在區域(函式)範圍內也可有def述句, 18 | return x ** 2 # 名稱bar位於foo_2的區域範圍內,不在全域範圍 19 | len = a * b + bar(c) # 在區域範圍內第一次指派名稱len,掩蓋住內建函式len 20 | return len 21 | # 此時尚未執行def bar(x):述句 22 | 23 | c = 5 # 在全域範圍內第一次指派名稱c 24 | m = foo_1(a, b) # 在全域範圍找到名稱foo_1,是個函式 25 | n = foo_2(a, b+2+len(li)) # 在內建範圍找到名稱len 26 | # 呼叫foo_2,進入foo_2函式的範圍,執行foo_2函式體, 27 | # 此時才定義函式bar(執行def述句),在foo_2範圍裡產生名稱bar 28 | 29 | # bar(3) # 若執行會發生「找不到名稱bar」的錯誤 30 | -------------------------------------------------------------------------------- /code_4/scope_counter.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/scope_counter.py -------------------------------------------------------------------------------- /code_4/scope_counter_shared.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def counter_shared(n): 5 | def inc(x): 6 | nonlocal n 7 | n += x 8 | return n 9 | 10 | def dec(x): 11 | nonlocal n 12 | n -= x 13 | return n 14 | 15 | return inc, dec 16 | 17 | c_inc, c_dec = counter_shared(60) 18 | print(c_inc(1)) # 61 19 | print(c_inc(4)) # 65 20 | print(c_dec(2)) # 63 21 | print(c_inc(5)) # 68 22 | print(c_dec(2)) # 66 23 | 24 | 25 | -------------------------------------------------------------------------------- /code_4/scope_default_arg_mutable.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/scope_default_arg_mutable.py -------------------------------------------------------------------------------- /code_4/scope_dynamic.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | b = 5 4 | def foo(): 5 | a = b + 5 6 | return a 7 | def bar(): 8 | b = 2 9 | return foo() 10 | 11 | print(foo()) 12 | print(bar()) 13 | -------------------------------------------------------------------------------- /code_4/scope_my_sqrt.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def my_sqrt(n): 4 | diff = 0.00001 5 | 6 | def is_good_enough(ans): 7 | return abs(ans**2 - n) < diff 8 | 9 | def get_better_ans(ans): 10 | return ((float(n) / ans) + ans) / 2 11 | 12 | ans = 1 13 | while not is_good_enough(ans): 14 | ans = get_better_ans(ans) 15 | return ans 16 | 17 | if __name__ == '__main__': 18 | import math 19 | print(my_sqrt(9), math.sqrt(9)) 20 | print(my_sqrt(2), math.sqrt(2)) 21 | print(my_sqrt(3), math.sqrt(3)) 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /code_4/scope_sorted.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # sorted(iterable[, key][, reverse]) 4 | 5 | t = (('Bob', 180, 80), ('Amy', 160, 60), ('Cathy', 170, 50)) 6 | 7 | NAME_I, HEIGHT_I, WEIGHT_I = range(3) 8 | 9 | def k_height(item): 10 | return item[HEIGHT_I] 11 | 12 | # def k_weight(item): 13 | # return item[WEIGHT_I] 14 | 15 | # print(sorted(t, key=k_height)) 16 | # print() 17 | 18 | def foo(data): 19 | HEIGHT_I = 99 20 | return sorted(data, key=k_height) 21 | 22 | print(foo(t)) 23 | 24 | 25 | 26 | #### 27 | print() 28 | 29 | print(sorted(t, key=lambda x: x[0])) # name 30 | print(sorted(t, key=lambda x: x[1])) # height 31 | print(sorted(t, key=lambda x: x[2])) # weight 32 | print() 33 | 34 | 35 | #### 36 | def sorted_by(data, what='name', reverse=False): 37 | d = {'name': 0, 'height': 1, 'weight': 2} 38 | i = d.get(what, 0) 39 | 40 | return sorted(data, key=lambda x: x[i], reverse=reverse) 41 | 42 | print(sorted_by(t, 'name')) 43 | print(sorted_by(t, 'height', reverse=True)) 44 | print(sorted_by(t, what='weight')) 45 | print(sorted_by(t, reverse=True)) 46 | -------------------------------------------------------------------------------- /code_4/test_hk.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/test_hk.txt -------------------------------------------------------------------------------- /code_4/tph.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Problem 45: Triangular, pentagonal, and hexagonal 4 | # https://projecteuler.net/problem=45 5 | 6 | def gen_n(f): 7 | i = 1 8 | while True: 9 | n = f(i) 10 | yield n 11 | i += 1 12 | 13 | def sub_gf(fa, fb): 14 | a = next(fa) 15 | b = next(fb) 16 | while True: 17 | if a < b: 18 | a = next(fa) 19 | elif a > b: 20 | b = next(fb) 21 | else: 22 | yield a 23 | a = next(fa) 24 | 25 | def tph(n): 26 | tn = gen_n(lambda i: i * (i+1) // 2) 27 | pn = gen_n(lambda i: i * (3*i - 1) // 2) 28 | hn = gen_n(lambda i: i * (2*i - 1)) 29 | 30 | sub1 = sub_gf(tn, pn) 31 | sub2 = sub_gf(sub1, hn) 32 | result = 0 33 | for i in range(n): 34 | result = next(sub2) 35 | return result 36 | 37 | # 38 | def test(): 39 | if tph(1) == 1 and tph(2) == 40755: 40 | return 'Pass' 41 | else: 42 | return 'Fail' 43 | 44 | def main(): 45 | return tph(3) 46 | 47 | if __name__ == '__main__': 48 | import sys 49 | if len(sys.argv) >= 2 and sys.argv[1] == 'test': 50 | print(test()) 51 | else: 52 | print(main()) 53 | 54 | -------------------------------------------------------------------------------- /code_4/unique_gf.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def unique(iterable, key=lambda x: x): 5 | seen = set() 6 | 7 | for elem, ekey in ((x, key(x)) for x in iterable): 8 | if ekey not in seen: 9 | yield elem 10 | seen.add(ekey) 11 | 12 | 13 | t = (1, 2, 5, 6, 7, 1, 2, 3, 6, 4, 3, 1, 2, 6) 14 | ug = unique(t) 15 | for x in ug: 16 | print(x) 17 | 18 | 19 | -------------------------------------------------------------------------------- /code_4/unique_set.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | li = (3, 1, 'a', 'Amy', 1, 3, 5, 'a') 4 | 5 | def unique(iterable): 6 | result = [] 7 | for x in iterable: 8 | if x not in result: 9 | result.append(x) 10 | return result 11 | 12 | print(unique(li)) 13 | print() 14 | 15 | print(set(li)) 16 | -------------------------------------------------------------------------------- /code_4/vase.txt: -------------------------------------------------------------------------------- 1 | 周杰倫 2 | 3 | 青花瓷 4 | 5 | 作詞:方文山 6 | 作曲:周杰倫 7 | 編曲:鍾興民 8 | 9 | 素胚勾勒出青花筆鋒濃轉淡 10 | 瓶身描繪的牡丹一如妳初妝 11 | 冉冉檀香透過窗心事我了然 12 | 宣紙上走筆至此擱一半 13 | 14 | 釉色渲染仕女圖韻味被私藏 15 | 而妳嫣然的一笑如含苞待放 16 | 妳的美一縷飄散 去到我去不了的地方 17 | 18 | 天青色等煙雨 而我在等妳 19 | 炊煙裊裊昇起 隔江千萬里 20 | 在瓶底書漢隸仿前朝的飄逸 21 | 就當我為遇見妳伏筆 22 | 23 | 天青色等煙雨 而我在等妳 24 | 月色被打撈起 暈開了結局 25 | 如傳世的青花瓷自顧自美麗 妳眼帶笑意 26 | 27 | 色白花青的錦鯉躍然於碗底 28 | 臨摹宋體落款時卻惦記著妳 29 | 妳隱藏在窯燒裡千年的秘密 30 | 極細膩猶如繡花針落地 31 | 32 | 簾外芭蕉惹驟雨門環惹銅綠 33 | 而我路過那江南小鎮惹了妳 34 | 在潑墨山水畫裡 妳從墨色深處被隱去 35 | 36 | -------------------------------------------------------------------------------- /code_4/vase_cp950.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/vase_cp950.txt -------------------------------------------------------------------------------- /code_4/vase_gbk.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_4/vase_gbk.txt -------------------------------------------------------------------------------- /code_4/vase_tr.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # with open('vase.txt', 'r', encoding='utf-8') as fin: 5 | # with open('vase_gbk.txt', 'w', encoding='gbk') as fout: 6 | # for line in fin: 7 | # fout.write(line) 8 | 9 | 10 | #### 11 | 12 | with open('vase_gbk.txt', 'r', encoding='gbk') as fin: 13 | with open('vase_cp950.txt', 'w', encoding='cp950') as fout: 14 | for line in fin: 15 | fout.write(line) 16 | -------------------------------------------------------------------------------- /code_4/yield_from_basic.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def gf(n): 4 | for i in range(1, n): 5 | yield i 6 | for i in range(-1, -n, -1): 7 | yield i 8 | 9 | print(list(gf(5))) 10 | 11 | #### 12 | def gf2(n): 13 | yield from range(1, n) 14 | yield from range(-1, -n, -1) 15 | 16 | print(list(gf2(5))) 17 | 18 | #### 19 | 20 | # chain # 21 | def chain(*iterables): 22 | for itb in iterables: 23 | yield from itb 24 | # for e in itb: 25 | # yield e 26 | 27 | r = range(5) 28 | li = ['a', 'b', 'c'] 29 | t = (0.1, 0.2, 0.3) 30 | for x in chain(r, li, t): 31 | print(x) 32 | 33 | -------------------------------------------------------------------------------- /code_5/A_B.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class A(): 4 | def __init__(self, x, y): 5 | self.x = x; self.y = y 6 | 7 | class B(A): 8 | def __init__(self, z): 9 | super().__init__(0, 0) 10 | self.z = z 11 | 12 | b = B(5) 13 | print(b.x, b.y, b.z) 14 | 15 | #### 16 | -------------------------------------------------------------------------------- /code_5/Card.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Card(): 4 | suits = {'spade': 4, 'heart': 3, 5 | 'diamond': 2, 'club': 1} 6 | ranks = {'A': 14, '2': 15, '3': 3, 7 | '4': 4, '5': 5, '6': 6, 8 | '7': 7, '8': 8, '9': 9, 9 | '10': 10, 'J': 11, 'Q': 12, 'K': 13} 10 | 11 | def __init__(self, suit, rank): 12 | self.suit = suit 13 | self.rank = rank 14 | 15 | def __lt__(self, other): 16 | rank_diff = Card.ranks[self.rank] - Card.ranks[other.rank] 17 | if rank_diff < 0: 18 | return True 19 | elif rank_diff == 0: 20 | if Card.ranks[self.rank] < Card.ranks[other.rank]: 21 | return True 22 | 23 | return False 24 | 25 | c1 = Card('spade', 'A') 26 | c2 = Card('spade', 'K') 27 | c3 = Card('heart', '9') 28 | c4 = Card('club', '2') 29 | print(c1 < c2) 30 | print(c2 < c3) 31 | print(c3 < c4) 32 | print(c4 < c1) 33 | -------------------------------------------------------------------------------- /code_5/Deck.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import random 4 | # from collections import abc 5 | 6 | # class Deck(abc.Sized, object): 7 | class Deck(object): 8 | cards_count = 52 9 | 10 | # spade, heart, diamond, club 11 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 12 | suits_shortname = 'SHDC' 13 | suit_count = 13 14 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 15 | 16 | def __init__(self): 17 | # 0~12 are Spade A~K, 18 | # 13~25 are Heart A~K, 19 | # 26~38 are Diamond A~K, 20 | # 39~51 are Club A~K 21 | # True means not-drawed-yet 22 | self.cards = list(range(Deck.cards_count)) 23 | # print(self.cards) 24 | 25 | def draw(self): 26 | card = '' 27 | if len(self.cards) > 0: 28 | i = random.randrange(len(self.cards)) 29 | card_n = self.cards.pop(i) 30 | q, r = divmod(card_n, Deck.suit_count) 31 | # print(card_n, q, r) 32 | card = ' '.join((Deck.suits[q], Deck.ranks[r])) 33 | 34 | return card 35 | 36 | def __iter__(self): 37 | return self 38 | 39 | def __next__(self): 40 | card = self.draw() 41 | if card != '': 42 | return card 43 | else: 44 | raise StopIteration('Deck is empty') 45 | 46 | def next(self): 47 | return self.__next__() 48 | 49 | def __len__(self): 50 | return len(self.cards) 51 | 52 | def __str__(self): 53 | return 'The deck remains %d cards.' % len(self.cards) 54 | 55 | if __name__ == '__main__': 56 | d = Deck() 57 | print(len(d)) 58 | for _ in range(5): 59 | print(d.draw()) 60 | print(len(d)) 61 | 62 | d2 = Deck() 63 | print(d2) 64 | d2.draw() 65 | print(d2) 66 | for card in d2: 67 | print(card) 68 | 69 | # print(next(d2)) 70 | # print(next(d2)) 71 | # print(d2) 72 | # print(issubclass(Deck, abc.Sized)) 73 | 74 | 75 | -------------------------------------------------------------------------------- /code_5/Deck_1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Deck(): 4 | pass 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /code_5/Deck_2.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Deck(object): 4 | pass 5 | 6 | d1 = Deck() 7 | print(d1) 8 | Deck.x = 3 9 | d1.y = 4 10 | print(Deck.x, d1.y) 11 | 12 | #### 13 | 14 | print(type(d1), type(Deck)) 15 | print(Deck.__name__) 16 | print(d1.__class__) 17 | print(Deck.__bases__) 18 | 19 | -------------------------------------------------------------------------------- /code_5/Deck_3.py: -------------------------------------------------------------------------------- 1 | 2 | import random 3 | 4 | class Deck(object): 5 | cards_count = 52 6 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 7 | suit_count = 13 8 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 9 | 10 | def __init__(self): 11 | li = list(range(Deck.cards_count)) 12 | random.shuffle(li) 13 | 14 | self.cards = tuple(li) 15 | 16 | # def __getitem__(self, i): 17 | def draw(self, i): 18 | if 0 <= i < Deck.cards_count: 19 | card_n = self.cards[i] 20 | q, r = divmod(card_n, Deck.suit_count) 21 | card = Deck.suits[q] + ' ' + Deck.ranks[r] 22 | return card 23 | else: 24 | raise IndexError('Index out of range') 25 | 26 | d1 = Deck() 27 | d2 = Deck() 28 | print('%10s %10s' % ('d1', 'd2')) 29 | for i in range(5): 30 | print('%10s %10s' % (d1.draw(i), d2.draw(i))) 31 | -------------------------------------------------------------------------------- /code_5/Deck_4.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | try: 4 | input = raw_input 5 | except NameError: 6 | pass 7 | 8 | import random 9 | 10 | class MyDeckIterator(object): 11 | def __init__(self, deck): 12 | self.deck = deck 13 | self.i = 0 14 | 15 | def __iter__(self): 16 | return self 17 | 18 | def __next__(self): 19 | try: 20 | card = self.deck[self.i] 21 | self.i += 1 22 | return card 23 | except IndexError: 24 | raise StopIteration('No more card') 25 | def next(self): 26 | return self.__next__() 27 | 28 | class MyDeck(object): 29 | cards_count = 52 30 | 31 | # spade, heart, diamond, club 32 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 33 | suit_count = 13 34 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 35 | 36 | def __init__(self): 37 | # 0~12 are Spade A~K, 38 | # 13~25 are Heart A~K, 39 | # 26~38 are Diamond A~K, 40 | # 39~51 are Club A~K 41 | # True means not-drawed-yet 42 | li = list(range(MyDeck.cards_count)) 43 | random.shuffle(li) 44 | 45 | self.cards = tuple(li) 46 | 47 | def __getitem__(self, i): 48 | if 0 <= i < MyDeck.cards_count: 49 | card_n = self.cards[i] 50 | q, r = divmod(card_n, MyDeck.suit_count) 51 | 52 | card = MyDeck.suits[q] + ' ' + MyDeck.ranks[r] 53 | return card 54 | else: 55 | raise IndexError('Index out of range') 56 | 57 | def __iter__(self): 58 | return MyDeckIterator(self) 59 | 60 | def __len__(self): 61 | return len(self.cards) 62 | 63 | def __str__(self): 64 | return 'The deck remains %d cards.' % len(self.cards) 65 | 66 | 67 | #### 68 | 69 | if __name__ == '__main__': 70 | d1 = MyDeck() 71 | # for i in range(MyDeck.cards_count): 72 | # print(d1[i]) 73 | # print(len(d1)) 74 | # print(len(d1)) 75 | 76 | # for card in d1: 77 | # print(card) 78 | # input('Press Entery to continue...') 79 | # for card in d1: 80 | # print(card) 81 | # input('Press Entery to continue...') 82 | 83 | # ditr_1 = iter(d1) 84 | # ditr_2 = iter(d1) 85 | 86 | # print('-' * 20) 87 | # print('ditr_1 ' + next(ditr_1)) 88 | # print('ditr_1 ' + next(ditr_1)) 89 | # print(' ditr_2 ' + next(ditr_2)) 90 | # print('ditr_1 ' + next(ditr_1)) 91 | # print(' ditr_2 ' + next(ditr_2)) 92 | # print('ditr_1 ' + next(ditr_1)) 93 | # print('ditr_1 ' + next(ditr_1)) 94 | # print(' ditr_2 ' + next(ditr_2)) 95 | # print('ditr_1 ' + next(ditr_1)) 96 | # print(' ditr_2 ' + next(ditr_2)) 97 | # print('-' * 20) 98 | 99 | # input('Press Entery to stop') 100 | 101 | -------------------------------------------------------------------------------- /code_5/Fibmemo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def fib_memo(): 4 | memo = {0: 0, 1: 1} 5 | def sub(n): 6 | if n not in memo: 7 | memo[n] = sub(n-1) + sub(n-2) 8 | return memo[n] 9 | return sub 10 | fib_m = fib_memo() 11 | 12 | #### 13 | 14 | class Fibmemo(): 15 | def __init__(self): 16 | self.memo = {0: 0, 1: 1} 17 | 18 | def __call__(self, n): 19 | if n not in self.memo: 20 | self.memo[n] = self(n-1) + self(n-2) 21 | return self.memo[n] 22 | 23 | fib = Fibmemo() 24 | print(fib(3), fib(5), fib(7)) 25 | 26 | 27 | #### context management protocol 28 | print() 29 | 30 | class Fib(): 31 | def __init__(self): 32 | self.memo = {0: 0, 1: 1} 33 | 34 | def __call__(self, n): 35 | if n not in self.memo: 36 | self.memo[n] = self(n-1) + self(n-2) 37 | return self.memo[n] 38 | 39 | def __enter__(self): 40 | self.memo = {0: 0, 1: 1} 41 | return self 42 | 43 | def __exit__(self, exc_type, exc_value, traceback): 44 | self.memo = {0: 0, 1: 1} 45 | return False # don't supress the exception 46 | 47 | with Fib() as fib: 48 | for n in range(1, 9+1): 49 | print('fib(%2d) = %4d, memo len is %2d' % (n, fib(n), len(fib.memo))) 50 | print(len(fib.memo)) 51 | 52 | with Fib() as fib: 53 | for n in range(1, 20+1): 54 | print('fib(%2d) = %4d, memo len is %2d' % (n, fib(n), len(fib.memo))) 55 | print(len(fib.memo)) 56 | -------------------------------------------------------------------------------- /code_5/MyDeck.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | try: 4 | input = raw_input 5 | except NameError: 6 | pass 7 | 8 | import random 9 | 10 | class MyDeckIterator(object): 11 | def __init__(self, deck): 12 | self.deck = deck 13 | self.i = 0 14 | 15 | def __iter__(self): 16 | return self 17 | 18 | def __next__(self): 19 | try: 20 | card = self.deck[self.i] 21 | self.i += 1 22 | return card 23 | except IndexError: 24 | raise StopIteration('No more card') 25 | def next(self): 26 | return self.__next__() 27 | 28 | class MyDeck(object): 29 | cards_count = 52 30 | 31 | # spade, heart, diamond, club 32 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 33 | suit_count = 13 34 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 35 | 36 | def __init__(self): 37 | # 0~12 are Spade A~K, 38 | # 13~25 are Heart A~K, 39 | # 26~38 are Diamond A~K, 40 | # 39~51 are Club A~K 41 | # True means not-drawed-yet 42 | li = list(range(MyDeck.cards_count)) 43 | random.shuffle(li) 44 | 45 | self.cards = tuple(li) 46 | 47 | def __getitem__(self, i): 48 | if 0 <= i < MyDeck.cards_count: 49 | card_n = self.cards[i] 50 | q, r = divmod(card_n, MyDeck.suit_count) 51 | 52 | card = MyDeck.suits[q] + ' ' + MyDeck.ranks[r] 53 | return card 54 | else: 55 | raise IndexError('Index out of range') 56 | 57 | def __iter__(self): 58 | return MyDeckIterator(self) 59 | 60 | def __len__(self): 61 | return len(self.cards) 62 | 63 | def __str__(self): 64 | return 'The deck remains %d cards.' % len(self.cards) 65 | 66 | 67 | #### 68 | 69 | if __name__ == '__main__': 70 | d1 = MyDeck() 71 | # for i in range(MyDeck.cards_count): 72 | # print(d1[i]) 73 | # print(len(d1)) 74 | # print(len(d1)) 75 | 76 | # for card in d1: 77 | # print(card) 78 | # input('Press Entery to continue...') 79 | # for card in d1: 80 | # print(card) 81 | # input('Press Entery to continue...') 82 | 83 | # ditr_1 = iter(d1) 84 | # ditr_2 = iter(d1) 85 | 86 | # print('-' * 20) 87 | # print('ditr_1 ' + next(ditr_1)) 88 | # print('ditr_1 ' + next(ditr_1)) 89 | # print(' ditr_2 ' + next(ditr_2)) 90 | # print('ditr_1 ' + next(ditr_1)) 91 | # print(' ditr_2 ' + next(ditr_2)) 92 | # print('ditr_1 ' + next(ditr_1)) 93 | # print('ditr_1 ' + next(ditr_1)) 94 | # print(' ditr_2 ' + next(ditr_2)) 95 | # print('ditr_1 ' + next(ditr_1)) 96 | # print(' ditr_2 ' + next(ditr_2)) 97 | # print('-' * 20) 98 | 99 | # input('Press Entery to stop') 100 | 101 | -------------------------------------------------------------------------------- /code_5/MyDeck_generator_expr.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import random 4 | 5 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 6 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 7 | 8 | deck = (suits[n//13] + ' ' + ranks[n%13] for n in random.sample(range(52), 52)) 9 | 10 | for _ in range(5): 11 | print(next(deck)) 12 | print('') 13 | 14 | #### 15 | 16 | deck = (('Spade', 'Heart', 'Diamond', 'Club')[n//13] + ' ' + 17 | ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')[n%13] 18 | for n in random.sample(range(52), 52)) 19 | 20 | for _ in range(5): 21 | print(next(deck)) 22 | -------------------------------------------------------------------------------- /code_5/MyDeck_gf.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | def deck_gf(): 5 | cards_count = 52 6 | suit_count = 13 7 | suits = ('Spade', 'Heart', 'Diamond', 'Club') 8 | ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K') 9 | 10 | import random 11 | li = list(range(cards_count)) 12 | random.shuffle(li) 13 | cards = tuple(li) 14 | 15 | i = 0 16 | while i < cards_count: 17 | card_n = cards[i] 18 | i += 1 19 | q, r = divmod(card_n, suit_count) 20 | card = suits[q] + ' ' + ranks[r] 21 | yield card 22 | 23 | #### 24 | deck_g = deck_gf() 25 | print(next(deck_g)) 26 | print(next(deck_g)) 27 | print(next(deck_g)) 28 | print(next(deck_g)) 29 | print(next(deck_g)) 30 | 31 | print('') 32 | 33 | for i, card in enumerate(deck_gf()): 34 | print(i, card) 35 | #### 36 | 37 | -------------------------------------------------------------------------------- /code_5/Person.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | class Person(): 5 | HI_STR = 'Hi, I am ' 6 | 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | def say_hello(self): 12 | print('Hello, I am ' + self.name) 13 | 14 | def say_hi(self): 15 | print(Person.HI_STR + self.name) 16 | 17 | 18 | 19 | p1 = Person('Amy', 25) 20 | p2 = Person('Bob', 38) 21 | p1.say_hello() 22 | Person.say_hello(p1) 23 | p2.say_hello() 24 | 25 | p1.say_hi() 26 | p2.say_hi() 27 | 28 | -------------------------------------------------------------------------------- /code_5/Person_2.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | class Person(): 5 | HI_STR = 'Hi, I am ' 6 | 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | def say_hello(self): 12 | print('Hello, I am ' + self.name) 13 | 14 | def say_hi(self): 15 | print(Person.HI_STR + self.name) 16 | 17 | def __str__(self): 18 | return ' %s, age %d' % (self.name, self.age) 19 | 20 | def __repr__(self): 21 | return "Person('%s', %d)" % (self.name, self.age) 22 | 23 | p1 = Person('Amy', 25) 24 | p2 = Person('Bob', 38) 25 | p1.say_hello() 26 | Person.say_hello(p1) 27 | p2.say_hello() 28 | 29 | p1.say_hi() 30 | p2.say_hi() 31 | 32 | print(p1) 33 | print(str(p2), p2.__str__()) 34 | print(repr(p1), p1.__repr__()) 35 | 36 | print() 37 | exec('p3 = ' + repr(p2)) 38 | print(p3) 39 | print(p3.name, p3.age) 40 | -------------------------------------------------------------------------------- /code_5/Person_property.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from datetime import datetime 4 | 5 | class Person(): 6 | def __init__(self, name, birthyear): 7 | self._name = name 8 | self._birthyear = birthyear 9 | 10 | def get_birthyear(self): 11 | return self._birthyear 12 | 13 | def set_birthyear(self, v): 14 | self._birthyear = v 15 | 16 | def del_birthyear(self): 17 | del self._birthyear 18 | 19 | birthyear = property(get_birthyear, set_birthyear, del_birthyear) 20 | 21 | p1 = Person('Amy', 2000) 22 | print(p1.get_birthyear()) 23 | p1.set_birthyear(2001) 24 | print(p1.get_birthyear()) 25 | 26 | p2 = Person('Bob', 1980) 27 | print(p2.birthyear) 28 | p2.birthyear = 1981 29 | print(p2.birthyear) 30 | 31 | #### 32 | 33 | class Person(): 34 | def __init__(self, name, birthyear): 35 | self._name = name 36 | self._birthyear = birthyear 37 | 38 | @property 39 | def birthyear(self): 40 | return self._birthyear 41 | 42 | @birthyear.setter 43 | def birthyear(self, v): 44 | self._birthyear = v 45 | 46 | @birthyear.deleter 47 | def birthyear(self): 48 | del self._birthyear 49 | 50 | p3 = Person('Cathy', 2010) 51 | print(p3.birthyear) 52 | p3.birthyear = 2011 53 | print(p3.birthyear) 54 | -------------------------------------------------------------------------------- /code_5/a.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def foo(li): li[99] 4 | def bar(li): tmp = foo(li) 5 | bar([0, 1, 2]) 6 | 7 | 8 | -------------------------------------------------------------------------------- /code_5/co_acc.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def acc_gf(n): 5 | while True: 6 | y = yield n 7 | n += 1 if y is None else y 8 | 9 | acc_g = acc_gf(100) 10 | print(next(acc_g)) 11 | print(acc_g.send(3)) 12 | print(next(acc_g)) 13 | print(acc_g.send(5)) 14 | 15 | -------------------------------------------------------------------------------- /code_5/except_foo_bar.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def foo(): 5 | try: 6 | raise ValueError 7 | except IndexError: 8 | print('foo IndexError') 9 | else: 10 | print('foo else') 11 | finally: 12 | print('foo finally') 13 | print('foo end') 14 | 15 | def bar(): 16 | try: 17 | foo() 18 | except ValueError: 19 | print('bar ValueError') 20 | else: 21 | print('bar else') 22 | finally: 23 | print('bar finally') 24 | print('bar end') 25 | 26 | bar() # what will be printed? 27 | -------------------------------------------------------------------------------- /code_5/except_reraise.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def reraise(): 4 | try: 5 | int('!@#') 6 | except ValueError as e: 7 | raise RuntimeError('parse error') from e 8 | # print(exc) 9 | 10 | reraise() 11 | 12 | # try: 13 | # reraise() 14 | # except RuntimeError as e: 15 | # print(e.__cause__) 16 | 17 | -------------------------------------------------------------------------------- /code_5/except_return.py: -------------------------------------------------------------------------------- 1 | 2 | def bar(): raise ValueError 3 | def foo(): 4 | try: 5 | bar() 6 | return 'try' 7 | except ValueError: 8 | return 'except' 9 | else: 10 | return 'else' 11 | finally: 12 | return 'finally' 13 | 14 | print(foo()) 15 | -------------------------------------------------------------------------------- /code_5/fact_exception_1.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | # int()與fact()都會引發ValueError 5 | 6 | def fact(n): 7 | if n < 0: 8 | raise ValueError('Argument must be non-negative') 9 | result = 1 10 | for i in range(1, n+1): 11 | result *= i 12 | return result 13 | 14 | while True: 15 | try: 16 | s = input('input n: ') 17 | sn = int(s) 18 | f = fact(sn) 19 | except ValueError as e: 20 | print('Error: ' + str(e)) 21 | except (EOFError, KeyboardInterrupt): 22 | print('\nBye') 23 | break 24 | except Exception as e: 25 | print('Unknown Error: ' + str(e)) 26 | else: 27 | print(str(sn) + '! = ' + str(f)) 28 | 29 | -------------------------------------------------------------------------------- /code_5/fact_exception_2.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | # class CustomError(Exception): 5 | # def __init__(self, message, status): 6 | # super().__init__(message, status) 7 | # self.message = message 8 | # self.status = status 9 | 10 | class NegativeIntError(ValueError): 11 | pass 12 | 13 | def fact(s): 14 | n = int(s, 0) 15 | if n < 0: 16 | raise NegativeIntError('Argument must be non-negative') 17 | 18 | result = 1 19 | for i in range(1, n+1): 20 | result *= i 21 | return (n, result) 22 | 23 | while True: 24 | try: 25 | s = input('input n: ') 26 | n, f = fact(s) 27 | except NegativeIntError as e: 28 | print('Error: ' + str(e)) 29 | except ValueError as e: 30 | print('Error: can not convert %s to integer' % s) 31 | except (EOFError, KeyboardInterrupt): 32 | print('\nBye') 33 | break 34 | except Exception as e: 35 | print('Unknown Error: ' + str(e)) 36 | else: 37 | print(str(n) + '! = ' + str(f)) 38 | 39 | -------------------------------------------------------------------------------- /code_5/fact_exception_3.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | def fact(n): 5 | if n < 0: 6 | raise ValueError('Argument must be non-negative') 7 | 8 | result = 1 9 | for i in range(1, n+1): 10 | result *= i 11 | return (n, result) 12 | 13 | while True: 14 | try: 15 | try: 16 | s = input('input n: ') 17 | if len(s) == 0: 18 | continue 19 | sn = int(s) 20 | except ValueError as e: 21 | print('Error: can not convert %s to integer' % s) 22 | continue 23 | 24 | n, f = fact(sn) 25 | except ValueError as e: 26 | print('Error: %s' % str(e)) 27 | except (EOFError, KeyboardInterrupt): 28 | print('\nBye') 29 | break 30 | except Exception as e: 31 | print('Unknown Error: ' + str(e)) 32 | else: 33 | print(str(n) + '! = ' + str(f)) 34 | 35 | -------------------------------------------------------------------------------- /code_5/fact_traditional.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def fact(n): 4 | if type(n) is not int: 5 | return -2 6 | if n < 0: 7 | return -1 8 | 9 | result = 1 10 | for i in range(1, n+1): 11 | result *= i 12 | return result 13 | 14 | while True: 15 | s = input('input n: ') 16 | n = int(s) # 17 | ans = fact(n) 18 | if ans == -2: 19 | print('Must input integer') 20 | elif ans == -1: 21 | print('Must be non-negative') 22 | else: 23 | print('%d! = %d' % (n, ans)) 24 | -------------------------------------------------------------------------------- /code_5/fl_ctof.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | tc = (0, 100, 30.2, 22.5, -15.8, 23.7) 5 | 6 | def ctof(c): # 攝氏轉華氏 7 | return c * 9.0 / 5.0 + 32 8 | 9 | itr_f = map(ctof, tc) 10 | 11 | for f in itr_f: 12 | print(f) 13 | 14 | #### 改用lambda 15 | print('') 16 | for f in map(lambda c: c*9.0/5.0+32, tc): 17 | print(f) 18 | 19 | #### zip原攝氏溫度與華氏溫度 20 | print('') 21 | for c, f in zip(tc, map(ctof, tc)): 22 | print(c, f) 23 | 24 | #### 運用產生器,自己寫map(功能較少) 25 | def my_map(func, itb): 26 | for e in itb: 27 | yield func(e) 28 | 29 | print('') 30 | for f in my_map(ctof, tc): 31 | print(f) 32 | 33 | -------------------------------------------------------------------------------- /code_5/fl_fact.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from functools import reduce 4 | 5 | # def mul(x, y): return x * y 6 | 7 | from operator import mul 8 | 9 | def fact(n): 10 | return reduce(mul, range(1, n+1), 1) 11 | 12 | 13 | -------------------------------------------------------------------------------- /code_5/fl_failed.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/fl_failed.py -------------------------------------------------------------------------------- /code_5/fl_odd_fibs.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/fl_odd_fibs.py -------------------------------------------------------------------------------- /code_5/fl_sq_even.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/fl_sq_even.py -------------------------------------------------------------------------------- /code_5/fl_tph.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Problem 45: Triangular, pentagonal, and hexagonal 4 | # https://projecteuler.net/problem=45 5 | 6 | from itertools import count 7 | # from itertools import imap as map # 2.x 8 | 9 | def tn(n): return n * (n+1) // 2 10 | def pn(n): return n * (3*n - 1) // 2 11 | def hn(n): return n * (2*n - 1) 12 | 13 | def filter_equal(ita, itb): 14 | a = next(ita) 15 | b = next(itb) 16 | while True: 17 | if a < b: 18 | a = next(ita) 19 | elif a > b: 20 | b = next(itb) 21 | else: 22 | yield a 23 | a = next(ita) 24 | 25 | def tph_gf(): 26 | while True: 27 | yield from filter_equal(map(hn, count(1)), 28 | filter_equal(map(tn, count(1)), 29 | map(pn, count(1)))) 30 | 31 | tph = tph_gf() 32 | print(next(tph)) # 1 33 | print(next(tph)) # 40755 34 | print(next(tph)) # 1533776805 35 | -------------------------------------------------------------------------------- /code_5/frange_class.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | class Frange(): 5 | def __init__(self, start, end=None, inc=None): 6 | self.start = float(start) # 避免某些情況出現int 7 | self.end = end 8 | self.inc = inc 9 | 10 | if self.end is None: # 傳入一個參數的情況 11 | self.end = self.start 12 | self.start = 0.0 13 | 14 | if self.inc is None: 15 | self.inc = 1.0 16 | 17 | def __iter__(self): # 既是Iterable、也是Iterator 18 | return self 19 | 20 | def __next__(self): 21 | x = self.start 22 | self.start += self.inc 23 | 24 | if abs(x) < abs(self.end): # 處理正、負的情況 25 | return x 26 | else: 27 | raise StopIteration 28 | 29 | #### 30 | 31 | for x in Frange(3): 32 | print(x) 33 | print() 34 | print(list(Frange(2.55, 3.7, 0.1))) 35 | print() 36 | print(list(Frange(0, 1, 0.1))) 37 | 38 | -------------------------------------------------------------------------------- /code_5/frange_gf.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | def frange(start, end=None, inc=None): 5 | start = float(start) 6 | 7 | if end is None: 8 | end = start 9 | start = 0.0 10 | 11 | if inc is None: 12 | inc = 1.0 13 | 14 | while abs(start) < abs(end): 15 | yield start 16 | start += inc 17 | 18 | #### 19 | 20 | 21 | for x in frange(3): 22 | print(x) 23 | print() 24 | print(list(frange(2.55, 3.7, 0.1))) 25 | print() 26 | print(list(frange(0, 1, 0.1))) 27 | 28 | -------------------------------------------------------------------------------- /code_5/futures_process.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import random 4 | from concurrent import futures 5 | import time 6 | from multiprocessing import freeze_support 7 | from functools import wraps 8 | 9 | # note: changed to use time.perf_counter() 10 | def timethis(func): 11 | @wraps(func) 12 | def wrapper(*args, **kwargs): 13 | start = time.perf_counter() 14 | r = func(*args, **kwargs) 15 | end = time.perf_counter() 16 | print('{}.{} : {}'.format(func.__module__, func.__name__, end - start)) 17 | return r 18 | return wrapper 19 | 20 | def fib(n): 21 | if n == 0 or n == 1: 22 | return n 23 | else: 24 | return fib(n-1) + fib(n-2) 25 | 26 | @timethis 27 | def foo(data): 28 | ans = [] 29 | for n in data: 30 | ans.append(fib(n)) 31 | return ans 32 | 33 | @timethis 34 | def bar(data): 35 | ans = [] 36 | with futures.ProcessPoolExecutor() as pool: 37 | for fibn in pool.map(fib, data): 38 | ans.append(fibn) 39 | return ans 40 | 41 | if __name__ == '__main__': 42 | freeze_support() 43 | print('Generating data...', end='') 44 | data = [] 45 | for _ in range(100): 46 | data.append(random.randint(1, 26)) 47 | print('done\n') 48 | 49 | print('Processing data iteratively...') 50 | foo(data) 51 | print('done\n') 52 | 53 | print('Processing data concurrently...') 54 | bar(data) 55 | print('done\n') 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /code_5/lex_perm.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Problem 24: Lexicographic permutations 4 | # https://projecteuler.net/problem=24 5 | 6 | # 7 | def perm_gf(s): 8 | if len(s) == 1: 9 | yield s[0] 10 | else: 11 | for i, c in enumerate(s): 12 | s_no_i = s[:i] + s[i+1:] 13 | for sub in perm_gf(s_no_i): 14 | yield c + sub 15 | 16 | # for i, x in enumerate(perm_gf('0123456789')): 17 | # if i < 4: 18 | # print(x) 19 | 20 | def lp_perm(s, nth): 21 | for i, x in enumerate(perm_gf(s)): 22 | if i == nth: 23 | return x 24 | 25 | #### 26 | def factorial(n): 27 | result = 1 28 | for i in range(1, n+1): 29 | result *= i 30 | return result 31 | 32 | def lp(s, nth): 33 | if nth == 0: 34 | return s 35 | else: 36 | seg = factorial(len(s) - 1) 37 | idx = nth // seg 38 | c = s[idx] 39 | stmp = s[:idx] + s[idx+1:] 40 | return c + lp(stmp, nth - idx*seg) 41 | 42 | # 43 | def test(): 44 | if (list(perm_gf('012')) == ['012', '021', '102', '120', '201', '210'] and 45 | lp('012', 5 - 1) == '201' and 46 | lp('0123456789', 10**6 - 1) == lp_perm('0123456789', 10**6 - 1)): 47 | return 'Pass' 48 | else: 49 | return 'Fail' 50 | 51 | def main(): 52 | return lp('0123456789', 10**6 - 1) 53 | 54 | if __name__ == '__main__': 55 | import sys 56 | if len(sys.argv) >= 2 and sys.argv[1] == 'test': 57 | print(test()) 58 | else: 59 | print(main()) 60 | 61 | -------------------------------------------------------------------------------- /code_5/max_so_far.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def max_so_far(m=0): 5 | def sub(x=m, *t): 6 | nonlocal m # 3.x 7 | x = max(t, default=x) 8 | if x > m: 9 | m = x 10 | return m 11 | return sub 12 | 13 | msf = max_so_far() 14 | print(msf(3)) 15 | print(msf(5)) 16 | print(msf(-1)) 17 | print(msf(6)) 18 | print(msf(33)) 19 | print(msf(11)) 20 | print(msf(67)) 21 | print(msf(-1)) 22 | -------------------------------------------------------------------------------- /code_5/method_decorator.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class MyClass(): 4 | @staticmethod 5 | def foo(arg1, arg2): 6 | return arg1 + arg2 7 | 8 | x = MyClass() 9 | print(x.foo(3, 4)) 10 | print(MyClass.foo(5, 6)) 11 | 12 | #### 13 | 14 | # class Unit(): 15 | # @classmethod 16 | 17 | 18 | #### 19 | -------------------------------------------------------------------------------- /code_5/mi.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class A(object): pass 4 | class B(object): pass 5 | class X(A, B): pass 6 | class Y(B, A): pass 7 | class Z(X, Y): pass 8 | -------------------------------------------------------------------------------- /code_5/myhello.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import mymath as m 4 | 5 | a, b = 26, 16 6 | 7 | if __name__ == '__main__': 8 | print(__name__) 9 | print(m.__name__) 10 | print(m.pi) 11 | print(m.gcd(a, b)) 12 | print(m.factorial(6)) 13 | 14 | 15 | -------------------------------------------------------------------------------- /code_5/myhello2.py: -------------------------------------------------------------------------------- 1 | 2 | from mymath2 import * 3 | # print(_x) # error 4 | 5 | from mymath2 import _y 6 | print(_y) # ok 7 | 8 | -------------------------------------------------------------------------------- /code_5/myhello3.py: -------------------------------------------------------------------------------- 1 | 2 | from mymath3 import * 3 | 4 | # print(_x) # error 5 | print(pi) 6 | # print(z) # error 7 | print(sq(9)) 8 | 9 | 10 | -------------------------------------------------------------------------------- /code_5/mymath.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | pi = 3.14 4 | 5 | def gcd(a, b): 6 | while b: 7 | a, b = b, a%b 8 | return a 9 | 10 | def factorial(n): 11 | result = 1 12 | for i in range(1, n+1): 13 | result *= i 14 | return result 15 | 16 | if __name__ == '__main__': 17 | print(__name__) 18 | 19 | 20 | -------------------------------------------------------------------------------- /code_5/mymath2.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | pi = 3.14 4 | _x = 5 5 | _y = 6 6 | 7 | -------------------------------------------------------------------------------- /code_5/mymath3.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | __all__ = ['pi', 'gcd', 'sq'] 4 | 5 | pi = 3.14 6 | _x = 5 7 | _y = 6 8 | z = 7 9 | def gcd(a, b): pass 10 | def sq(n): return n**2 11 | 12 | -------------------------------------------------------------------------------- /code_5/open_file.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import sys 4 | import errno 5 | 6 | if len(sys.argv) != 2: 7 | print('Usage: %s input_filename' % __file__) 8 | sys.exit() 9 | 10 | try: 11 | with open(sys.argv[1], 'r', encoding='utf-8') as fin: 12 | for i, line in enumerate(iter(fin.readline, '\n')): 13 | print('%03d %s' % (i+1, line), end='') 14 | except OSError as e: 15 | if e.errno == errno.ENOENT: 16 | print('File %s does not exist.' % sys.argv[1]) 17 | elif e.errno == errno.EACCES: 18 | print('No permission to read the file %s.', sys.argv[1]) 19 | elif e.errno == errno.EISDIR: 20 | print('%s is not a file.' % sys.argv[1]) 21 | except UnicodeDecodeError: 22 | print('%s is not a UTF-8-encoded text file.' % sys.argv[1]) 23 | except Exception as e: 24 | print('Unknown Error: ' + str(e)) 25 | 26 | #### 27 | # try: 28 | # with open(sys.argv[1], 'r', encoding='utf-8') as fin: 29 | # for i, line in enumerate(fin): 30 | # print('%03d %s' % (i+1, line), end='') 31 | # except FileNotFoundError: 32 | # print('File %s does not exist.' % sys.argv[1]) 33 | # except PermissionError: 34 | # print('No permission to read the file %s.', sys.argv[1]) 35 | # except IsADirectoryError: 36 | # print('%s is not a file.' % sys.argv[1]) 37 | # except UnicodeDecodeError: 38 | # print('%s is not a UTF-8-encoded text file.' % sys.argv[1]) 39 | # except Exception as e: 40 | # print('Unknown Error: ' + str(e)) 41 | -------------------------------------------------------------------------------- /code_5/package_example/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # from .. import * # error 5 | 6 | -------------------------------------------------------------------------------- /code_5/package_example/formats/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | return 'foo' 4 | -------------------------------------------------------------------------------- /code_5/package_example/formats/bar.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def square(x): 4 | return x * x 5 | -------------------------------------------------------------------------------- /code_5/package_example/formats/bmp.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/package_example/formats/bmp.py -------------------------------------------------------------------------------- /code_5/package_example/formats/foo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import sys 4 | sys.path.append('/cygdrive/d/yehnan/wr_python_drmaster/python_book_yehnan/ch10') 5 | 6 | # import package_example.formats.bar 7 | # square = package_example.formats.bar.square 8 | 9 | # from bar import square 10 | 11 | from . import bar 12 | square = bar.square 13 | 14 | # from .bar import square 15 | 16 | 17 | def sos(a, b): 18 | return square(a) + square(b) 19 | 20 | 21 | if __name__ == '__main__': 22 | if sos(3, 4) != 25: 23 | print('error') 24 | else: 25 | print('ok') 26 | 27 | 28 | -------------------------------------------------------------------------------- /code_5/package_example/formats/jpg.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from . import bar 4 | from .. import info 5 | from ..gui import display 6 | from ..gui import menu 7 | from ..gui.canvas import * 8 | 9 | print(bar.__name__) 10 | print(info.__name__) 11 | print(display()) 12 | print(menu.__name__) 13 | print(clear()) 14 | 15 | -------------------------------------------------------------------------------- /code_5/package_example/formats/png.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/package_example/formats/png.py -------------------------------------------------------------------------------- /code_5/package_example/gui/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | __all__= ['menu', 'canvas', 'display', 'draw'] 4 | 5 | def display(): 6 | return 'display' 7 | def draw(): 8 | return 'draw' 9 | 10 | 11 | -------------------------------------------------------------------------------- /code_5/package_example/gui/canvas.py: -------------------------------------------------------------------------------- 1 | 2 | def clear(): 3 | return 'clear' 4 | -------------------------------------------------------------------------------- /code_5/package_example/gui/menu.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /code_5/package_example/info.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/package_example/info.py -------------------------------------------------------------------------------- /code_5/package_example/tools/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # from foo import * # 2.x 4 | # from bar import * # 2.x 5 | 6 | # from package_example.tools.foo import * 7 | # from package_example.tools.bar import * 8 | 9 | from .foo import * 10 | from .bar import * 11 | 12 | -------------------------------------------------------------------------------- /code_5/package_example/tools/bar.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def bar(): 4 | return 'bar' 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /code_5/package_example/tools/foo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def foo(): 4 | return 'foo' 5 | 6 | -------------------------------------------------------------------------------- /code_5/package_example/tools/rotate.py: -------------------------------------------------------------------------------- 1 | 2 | def rotate(): 3 | return 'rotate' 4 | 5 | -------------------------------------------------------------------------------- /code_5/package_example/tools/xyz/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | from ... import info 5 | 6 | print(info.__name__) 7 | -------------------------------------------------------------------------------- /code_5/package_example_main.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # import package_example.gui.menu 5 | # import package_example.gui.menu as menu 6 | # import package_example.gui.canvas 7 | # from package_example.gui import * 8 | 9 | # from package_example import info 10 | # from package_example import gui 11 | # print(info.__name__) 12 | # print(gui.__name__) 13 | 14 | 15 | # print(display()) 16 | # print(draw()) 17 | # print(menu.__name__) 18 | # print(canvas.__name__) 19 | 20 | 21 | # print(canvas.__name__) 22 | # print(menu.__name__) 23 | 24 | # import package_example.formats.foo 25 | # print(type(package_example.formats.foo)) 26 | 27 | # from package_example.formats import foo 28 | # print(type(foo)) 29 | 30 | # import package_example.tools 31 | # print(package_example.tools.foo()) 32 | # print(package_example.tools.bar()) 33 | 34 | # from package_example.tools import rotate 35 | # print(rotate.rotate()) 36 | 37 | # import package_example.formats.jpg 38 | # import package_example.formats.bar 39 | # print(package_example.formats.bar.__name__) 40 | 41 | # import package_example 42 | 43 | # import package_example.tools.xyz 44 | 45 | # from . import info 46 | # print(info.__name__) 47 | 48 | # import package_example.formats.foo 49 | # print(package_example.formats.foo.sos(3, 4)) 50 | # print(package_example.__path__) 51 | 52 | from package_example.formats import foo 53 | print(type(foo)) 54 | 55 | -------------------------------------------------------------------------------- /code_5/perm.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | from itertools import permutations 4 | p = permutations 5 | 6 | def perm(iterable, r=None): 7 | items = tuple(iterable) # 欲排列的東西 8 | r = len(items) if r is None else r 9 | 10 | answers = [] # 存放結果的串列 11 | 12 | def sub(items, k, p): # 從items裡取出k個,p是目前已有的排列 13 | if k == 0: 14 | answers.append(p) 15 | else: 16 | for i in range(len(items)): 17 | # 遞迴呼叫,去掉索引i的元素 18 | sub(items[:i] + items[i+1:], k-1, p+(items[i],)) 19 | sub(items, r, ()) 20 | 21 | return answers 22 | 23 | #### 24 | 25 | def perm_gf(iterable, r=None, p=()): 26 | items = tuple(iterable) 27 | n = len(items) 28 | r = n if r is None else r 29 | 30 | if r == 0: 31 | yield p 32 | else: 33 | for i in range(n): 34 | yield from perm_gf(items[:i] + items[i+1:], r-1, p+(items[i],)) 35 | # for perm in perm_gf(items[:i] + items[i+1:], r-1, p+(items[i],)): 36 | # yield perm 37 | 38 | #### 39 | if __name__ == '__main__': 40 | tests = (list(range(3)), ['a','b','c','d'], list(range(100, 106))) 41 | for t in tests: 42 | pa = list(p(t)) 43 | pb = perm(t) 44 | pc = tuple(perm_gf(t)) 45 | if set(pa) == set(pb) == set(pc): 46 | print('yes') 47 | else: 48 | print('no') 49 | for t in tests: 50 | for r in range(1, len(t)): 51 | pa = list(p(t, r)) 52 | pb = perm(t, r) 53 | pc = tuple(perm_gf(t, r)) 54 | if set(pa) == set(pb) == set(pc): 55 | print('yes') 56 | else: 57 | print('no') 58 | -------------------------------------------------------------------------------- /code_5/private_name.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class A(): 4 | def __init__(self): 5 | self.x = 3 6 | self.__pi = 3.14 7 | def foo(self): 8 | print(self.__pi) 9 | 10 | class B(A): 11 | def __init__(self): 12 | super().__init__() 13 | self.z = self.x + 100 14 | 15 | def bar(self): 16 | # return self.__pi # error 17 | return self._A__pi # ok 18 | a = A() 19 | b = B() 20 | print(b.x,b.z) 21 | # print(a.__pi) # error 22 | a.foo() 23 | print(b.bar()) 24 | 25 | -------------------------------------------------------------------------------- /code_5/queen_basic.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | def queen(n): 4 | answers = [] 5 | 6 | # 已有部分擺法ans,判斷是否可在下一列的第col欄擺上皇后 7 | def is_safe(ans, col): 8 | for i, c in enumerate(ans): 9 | if len(ans)-i == abs(c-col): 10 | return False 11 | return True 12 | 13 | # def is_safe(ans, col): 14 | # return all([not len(ans)-i == abs(c-col) 15 | # for i, c in enumerate(ans)]) 16 | 17 | # 遞迴 18 | def sub(ans): 19 | if len(ans) == n: # 已擺入n個皇后 20 | answers.append(ans) 21 | else: 22 | for col in range(n): # 逐一判斷要把皇后擺在次列的第0~(n-1)欄 23 | if col not in ans and is_safe(ans, col): 24 | sub(ans + (col,)) # 若可以,加入答案,繼續下次遞迴 25 | 26 | sub(()) # 一開始ans是()空tuple,什麼都還沒擺 27 | return answers 28 | 29 | #### 30 | def is_safe(ans, col): 31 | for i, c in enumerate(ans): 32 | if len(ans)-i == abs(c-col): 33 | return False 34 | return True 35 | 36 | def queen_gf(n, ans=()): 37 | 38 | if len(ans) == n: 39 | yield ans 40 | else: 41 | for col in range(n): 42 | if col not in ans and is_safe(ans, col): 43 | yield from queen_gf(n, (ans + (col,))) 44 | 45 | #### 46 | if __name__ == '__main__': 47 | n = 8 48 | answers = queen(n) 49 | for ans in answers: 50 | print(ans) 51 | print(len(answers)) 52 | print('-' * 20) 53 | answers2 = tuple(queen_gf(n)) 54 | if set(answers) == set(answers2): 55 | print('yes') 56 | else: 57 | print('no') 58 | print(len(answers2)) 59 | 60 | -------------------------------------------------------------------------------- /code_5/queen_hettingers_gf.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Raymond Hettingers 4 | # http://code.activestate.com/recipes/576647/ 5 | from itertools import permutations 6 | 7 | def queen_gf(n): 8 | cols = range(n) 9 | for ans in permutations(cols): 10 | if (n == len(set(ans[i]+i for i in cols)) == 11 | len(set(ans[i]-i for i in cols))): 12 | yield ans 13 | -------------------------------------------------------------------------------- /code_5/text_big5.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/text_big5.txt -------------------------------------------------------------------------------- /code_5/text_utf16be.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/text_utf16be.txt -------------------------------------------------------------------------------- /code_5/text_utf8.txt: -------------------------------------------------------------------------------- 1 | 你好 2 | hello python 3 | 123 4 | 床前明月光 疑是地上霜 5 | 6 | 舉頭望明月,低頭思故鄉 7 | 456 8 | def 9 | -------------------------------------------------------------------------------- /code_5/tiger.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class MyClass(): 4 | def __init__(self): self.x = 3 5 | def foo(self): 6 | self.x += 1; print(self.x) 7 | def bar(tiger, n): 8 | tiger.x += n; print(tiger.x) 9 | 10 | c = MyClass() 11 | c.foo() # ? 12 | MyClass.foo(c) # ? 13 | c.bar(-2) # ? 14 | MyClass.bar() # ? 15 | c.foo(c) # ? 16 | -------------------------------------------------------------------------------- /code_5/tph.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Problem 45: Triangular, pentagonal, and hexagonal 4 | # https://projecteuler.net/problem=45 5 | 6 | def gen_n(f): 7 | i = 1 8 | while True: 9 | n = f(i) 10 | yield n 11 | i += 1 12 | 13 | def sub_gf(fa, fb): 14 | a = next(fa) 15 | b = next(fb) 16 | while True: 17 | if a < b: 18 | a = next(fa) 19 | elif a > b: 20 | b = next(fb) 21 | else: 22 | yield a 23 | a = next(fa) 24 | 25 | def tph(n): 26 | tn = gen_n(lambda i: i * (i+1) // 2) 27 | pn = gen_n(lambda i: i * (3*i - 1) // 2) 28 | hn = gen_n(lambda i: i * (2*i - 1)) 29 | 30 | sub1 = sub_gf(tn, pn) 31 | sub2 = sub_gf(sub1, hn) 32 | result = 0 33 | for i in range(n): 34 | result = next(sub2) 35 | return result 36 | 37 | # 38 | def test(): 39 | if tph(1) == 1 and tph(2) == 40755: 40 | return 'Pass' 41 | else: 42 | return 'Fail' 43 | 44 | def main(): 45 | return tph(3) 46 | 47 | if __name__ == '__main__': 48 | import sys 49 | if len(sys.argv) >= 2 and sys.argv[1] == 'test': 50 | print(test()) 51 | else: 52 | print(main()) 53 | 54 | -------------------------------------------------------------------------------- /code_5/unique_gf.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def unique(iterable, key=lambda x: x): 5 | seen = set() 6 | 7 | for elem, ekey in ((x, key(x)) for x in iterable): 8 | if ekey not in seen: 9 | yield elem 10 | seen.add(ekey) 11 | 12 | 13 | t = (1, 2, 5, 6, 7, 1, 2, 3, 6, 4, 3, 1, 2, 6) 14 | ug = unique(t) 15 | for x in ug: 16 | print(x) 17 | 18 | 19 | -------------------------------------------------------------------------------- /code_5/unique_set.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | li = (3, 1, 'a', 'Amy', 1, 3, 5, 'a') 4 | 5 | def unique(iterable): 6 | result = [] 7 | for x in iterable: 8 | if x not in result: 9 | result.append(x) 10 | return result 11 | 12 | print(unique(li)) 13 | print() 14 | 15 | print(set(li)) 16 | -------------------------------------------------------------------------------- /code_5/weather_hsinchu.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | 4 | from __future__ import print_function 5 | from io import open 6 | 7 | import requests 8 | from lxml import html 9 | # from lxml.html import soupparser 10 | # from bs4 import BeautifulSoup 11 | 12 | url = 'http://www.cwb.gov.tw/V7/forecast/taiwan/Hsinchu_City.htm' 13 | 14 | r = requests.get(url) 15 | print(r.status_code) 16 | print(r.headers['content-type']) 17 | print(r.encoding) 18 | r.encoding = 'utf-8' 19 | print(type(r.text), len(r.text)) 20 | # print(r.text) 21 | 22 | # root = soupparser.fromstring(r.text) # parse 23 | root = html.fromstring(r.text) # parse 24 | # print(type(root)) 25 | print('-' * 20) 26 | 27 | 28 | # 'body/div/div/div/div/div/div/h3' class="CenterTitle" 29 | el_issued = root.find('body/div/div/div/div/div/div/h3/span') 30 | print(el_issued.text) 31 | print('-' * 20) 32 | 33 | 34 | el_table = root.find('body/div/div/div/div/div/div/table') 35 | for el_ths in el_table.findall('thead/tr/th'): 36 | print('{: <9s}'.format(el_ths.text.strip()), end='') 37 | print() 38 | 39 | for el_trs in el_table.findall('tbody/tr'): 40 | th = el_trs.find('th') 41 | print('{: <9s}'.format(th.text.split()[0]), end='') 42 | for td in el_trs.findall('td'): 43 | if td.find('img') is not None and td.find('img').get('title'): 44 | print('{: <9s}'.format(td.find('img').get('title').strip()), end='') 45 | else: 46 | print('{: <9s}'.format(td.text.strip()), end='') 47 | print() 48 | print() 49 | 50 | 51 | #### 52 | 53 | # def count_eng(s): 54 | # return sum(1 for c in s if ord(c) <= 127) 55 | 56 | # el_table = root.find('body/div/div/div/div/div/div/table') 57 | # for el_ths in el_table.findall('thead/tr/th'): 58 | # s = el_ths.text.strip() 59 | # count = count_eng(s) 60 | # print('{: <{cnt}s}'.format(s, cnt=7+count), end='') 61 | # print() 62 | 63 | # for el_trs in el_table.findall('tbody/tr'): 64 | # th = el_trs.find('th') 65 | # print('{: <9s}'.format(th.text.split()[0]), end='') 66 | # for td in el_trs.findall('td'): 67 | # if td.find('img') is not None and td.find('img').get('title'): 68 | # print('{: <9s}'.format(td.find('img').get('title').strip()), end='') 69 | # else: 70 | # print('{: <9s}'.format(td.text.strip()), end='') 71 | # print() 72 | # print() 73 | 74 | -------------------------------------------------------------------------------- /code_5/weather_hsinchu.py_all_a.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/weather_hsinchu.py_all_a.txt -------------------------------------------------------------------------------- /code_5/weather_hsinchu.py_all_b.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/code_5/weather_hsinchu.py_all_b.txt -------------------------------------------------------------------------------- /code_5/while_else.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a = 3 4 | n = 9 5 | while a < n: 6 | print(a) 7 | a += 1 8 | # if a == 5: 9 | # break 10 | else: 11 | print('hello') 12 | 13 | 14 | -------------------------------------------------------------------------------- /py01_intro.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py01_intro.pdf -------------------------------------------------------------------------------- /py02_basic_part1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py02_basic_part1.pdf -------------------------------------------------------------------------------- /py02_basic_part2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py02_basic_part2.pdf -------------------------------------------------------------------------------- /py02_basic_part3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py02_basic_part3.pdf -------------------------------------------------------------------------------- /py02_basic_part4_ex.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py02_basic_part4_ex.pdf -------------------------------------------------------------------------------- /py03_numeric.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py03_numeric.pdf -------------------------------------------------------------------------------- /py04_container_part1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py04_container_part1.pdf -------------------------------------------------------------------------------- /py04_container_part1b.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py04_container_part1b.pdf -------------------------------------------------------------------------------- /py04_container_part2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py04_container_part2.pdf -------------------------------------------------------------------------------- /py05_function_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py05_function_1.pdf -------------------------------------------------------------------------------- /py05_function_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py05_function_2.pdf -------------------------------------------------------------------------------- /py05_function_3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py05_function_3.pdf -------------------------------------------------------------------------------- /py05_function_4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py05_function_4.pdf -------------------------------------------------------------------------------- /py06_str_format.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py06_str_format.pdf -------------------------------------------------------------------------------- /py07_file_bytes_encoding.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py07_file_bytes_encoding.pdf -------------------------------------------------------------------------------- /py08_class.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py08_class.pdf -------------------------------------------------------------------------------- /py09_module.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py09_module.pdf -------------------------------------------------------------------------------- /py10_exception.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py10_exception.pdf -------------------------------------------------------------------------------- /py11_others.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yehnan/python_book_slides/69e552e4c786ba1c11267f1f668e5d48146d75f2/py11_others.pdf --------------------------------------------------------------------------------