# SC 2020 Python初階兩天 ## code1 ```python= import sys import os print(f"my python is:{sys.executable}") print("my python is:{}".format(sys.executable)) print("my python is:%s" % (sys.executable)) print(f"my python script is:{sys.argv[0]}") print(f"my working directory:{os.getcwd()}") print("env check success") ``` ## code2 ```python= # 這行是註解 # ctrl+alt+L x = (1 + 2) * (3 + 4) / (5 + 6) ** 7 print(x) a = 2 ** 32 print(a) b = 2 ** 64 print(b) print(5 ** 2, 5 ** 3, 5 ** 4) print(2 ** 5, 3 ** 5, 4 ** 5) print(5 ^ 2, 5 ^ 3, 5 ^ 4) print(2 ^ 5, 3 ^ 5, 4 ^ 5) ``` https://www.sympy.org/en/index.html https://pytorch.org/ https://caffe.berkeleyvision.org/ ## code4 ```python= x1 = ['apple', 'banana'] x2 = ['cake', 'donut'] print(x1 + x2) y1 = [100, 200] y2 = [300, 400] print(f"list+list={y1 + y2}") import numpy as np print(f"my numpy version={np.__version__}") v1 = np.array(y1) v2 = np.array(y2) print(f"vector+vector={v1+v2}") ``` ## numpy website https://www.lfd.uci.edu/~gohlke/pythonlibs/ ## code5 ```python= if __name__ == '__main__': print('this is my main program') ``` ## demo6_ds1 ```python= v1 = [] v2 = () v3 = {} print(type(v1), type(v2), type(v3)) v4 = ['a', 'b', 'c'] v5 = ['d', 'e', 'f'] print(v1, v4, v5) v6 = v4 print(v4, v6) v4[0] = 'A' v6[2] = 'C' print(v4, v6) print(len(v4), len(v6)) ``` ## Demo7 ```python= l1 = list("ABCDEFG1234567") print(type(l1), l1) print(l1[0], l1[len(l1) - 1]) print(l1[-1], l1[-len(l1)]) # print(l1[len(l1)]) # avoid OOR Exception # print(l1[-len(l1) - 1]) print(l1[2:5]) print(l1[:5]) print(l1[7:]) print(l1[:-6], l1[-6:]) print(l1[::2]) ``` ## Demo8 ```python= l1 = [1, 2, 3, 4, 5] print(l1 + l1) print(l1 * 3) print(3 * l1) for l in l1: print(l) l2 = ['apple', 'banana', 'cake', 'donut'] for l in l2: print(l) print([l ** l for l in l1]) print([f"{l}-({len(l)})" for l in l2 if len(l) > 5]) ``` ## Demo9 ```python= l1 = ['P', 'Q', 'R'] l2 = l1 l3 = l1 l4 = l1[:] l5 = list(l1) print(l1, l2, l3, l4, l5) print(f"l1 id={hex(id(l1))}, l2 id={hex(id(l2))}") print(l1 is l2, l1 is l3, l1 is l4, l1 is l5) print(l1 == l2, l1 == l3, l1 == l4, l1 == l5) ## l1[0] = 'a' print(l1, l2, l3, l4) l2 = l1 * 3 # allocate to a new address print(f"l1 id={hex(id(l1))}, l2 id={hex(id(l2))}") print(l1, l2, l3, l4) ``` ## demo10_mutability ```python= x1 = 5 print(f'x1={x1},id={hex(id(x1))}') x1 = 7 print(f'x1={x1}, id={hex(id(x1))}') y1 = [5] print(f'y1={y1}, id={hex(id(y1))}') print(f'y1[0]={hex(id(y1[0]))}') y1[0] = 7 print(f'y1={y1}, id={hex(id(y1))}') print(f'y1[0]={hex(id(y1[0]))}') ``` ## demo11_tuple1 ```python= x1 = [] x2 = () print(type(x1), type(x2)) x1 = [1, 2, 3, 4, 5] x2 = (1, 2, 3, 4, 5) print([x ** 2 for x in x1]) print([x ** 2 for x in x2]) x1[0] = 100 print(x1) # x2[0] = 100 x3 = list('12345') x3 = [int(x) for x in x3] print([x ** 2 for x in x3]) x4 = [1, 2, 3, 4, 5] ``` ## demo12_tuple_list ```python= x1 = (1, 2) y1 = [1, 2] x2 = (3, 4) y2 = [3, 4] print(f"before,x1={hex(id(x1))}, y1={hex(id(y1))}") print(x1 + x2) print(y1 + y2) x1 = x1 + x2 y1 = y1 + y2 print(f"before,x1={hex(id(x1))}, y1={hex(id(y1))}") print(x1) print(y1) z1 = (5, 6, 7) z1 += (8,) print(z1) print(id(z1)) p = 20000 print(f"Decimal={p}, Hex={hex(p)}") ``` ## Demo_tuple2 ```python= x1 = 5 x2 = 7 print(f'Before, x1={x1}, x2={x2}') t = x1 x1 = x2 x2 = t print(f'After, x1={x1}, x2={x2}') x3 = 5 x4 = 7 print(f'Before, x3={x3}, x4={x4}') x3, x4 = x4, x3 print(f'after, x3={x3}, x4={x4}') x5 = 100 x6 = "Hello World" print(f'Before, x3={x5}, x4={x6}') x5, x6 = x6, x5 print(f'after, x3={x5}, x4={x6}') x7, x8, x9 = ['Hello', 'hi', 'Welcome'] print(x9, x8, x7) C1, C2, C3, C4, C5 = ['A', 'K', 'Q', 'J', '10'] C1, C3, C5, C4, C2 = C5, C4, C3, C2, C1 print(C1, C2, C3, C4, C5) ``` ## demo14_pass_list_as_parameter ```python= def addAnimal(parameter): parameter.append('Zebra') animals = ['alpaca', 'baboon'] addAnimal(animals) print(animals) ``` ## demo15_list_copy ```python= from copy import copy, deepcopy player1 = [['A', 'K'], ['Q', 'J', '10']] player2 = player1 player3 = copy(player1) player4 = deepcopy(player1) print(player1, player2, player3, player4) print(player1 == player2, player1 == player3, player1 == player4) print(player1 is player2, player1 is player3, player1 is player4) player1.append('Joker') print(player1, player2, player3, player4) player1[0][0] = 8 print(player1, player2, player3, player4) ``` ## demo16_dict1 ```python= d1 = {} d2 = {'name': 'POOP', 'duration': 35} d3 = {'duration': 35, 'name': 'POOP'} d4 = dict(name='POOP', duration=35) d5 = dict([('name', 'POOP'), ('duration', 35)]) print(type(d1), type(d2), type(d3), type(d4), type(d5)) print(d2 == d3, d2 == d4, d2 == d5) ``` ## demo17 ```python= salesReport = {'iphone11': 500, 'iphone11+': 300, 'ipad': 400, 'applewatch': 300} for s in salesReport: print(s) print([key for key in salesReport]) print([k for k in salesReport.keys()]) print([v for v in salesReport.values()]) for item in salesReport.items(): print(type(item), item) print(item[0], item[1]) print([f"item key={k}, value={v}" for k, v in salesReport.items()]) ``` ## demo18_dict_default ```python= sales = ['S', 'S', 'M', 'L', 'S', 'M', 'L', 'S', 'M', 'L', 'S', 'S', 'S', 'XL', 'SS'] count = {} # count = {'S': 0, 'M': 0, 'L': 0} for s in sales: count.setdefault(s, 0) count[s] = count[s] + 1 print(count) sales2 = [('S', 20), ('M', 30), ('L', 40), ('M', 20), ('S', 30)] count2 = {} for type, quantity in sales2: count2.setdefault(type, 0) count2[type] = count2[type] + quantity print(count2) ``` ## demo19_set1 ```python= s1 = {'hello'} s2 = {} # empty dictionart s3 = set() # empty set print(type(s1), type(s2), type(s3)) print(len(s1), len(s2), len(s3)) s4 = {'A', 'P', 'P', 'L', 'E'} print(s4) s5 = {'B', 'A', 'N', 'A', 'N', 'A'} print(s5) print(f"using |, answer={s4 | s5}") # union print(f"using| with sorted, answer={sorted((s4 | s5))}") print(s4 & s5) print(s4 ^ s5) print(f"union (intersection) and (XOR), answer={(s4^s5)|(s4&s5)}") print(f's4={s4},s4 id={hex(id(s4))}') s4.add('X') print(f's4={s4},s4 id={hex(id(s4))}') s4.remove('X') print(f's4={s4},s4 id={hex(id(s4))}') # s4.remove('X') ``` ## demo20_set_remove ```python= jj_a1 = {'key1': ('P', 'Q', 'R')} print(jj_a1) for k in jj_a1: print(f'[1]key={k},value={jj_a1[k]}') for k, v in jj_a1.items(): print(f'[2]key={k},value={v}') s1 = set(list('APPLE')) find = 'A' print(s1) print(f'A in s1?{find in s1}') # s1.remove('A') print(s1) if find in s1: s1.remove(find) print(s1) s2 = set(list('PINEAPPLE')) removeString = 'ABCED' for f in removeString: f in s2 and s2.remove(f) print(s2) ``` ## demo21_set2 ```python= s1 = {'A', 'P', 'P', 'L', 'E'} s2 = set(list('APPLE')) s3 = {'E', 'L', 'A', 'P', 'P', 'P', 'P', 'P'} s4 = s1 print(s1, s2, s3) print(s1 == s2, s1 == s3, s1 == s4) print(s1 is s2, s1 is s3, s1 is s4) ``` ## demo22_set3 ```python= s1 = {'A', 'B'} itemsNeedToAdd = [3.14, 'hello world', 500, None, 3 + 5j, 'k', ('Sunday',), ('TSMC', 'UMC')] for item in itemsNeedToAdd: s1.add(item) print(s1) # object in set s2 = set() class Training: def __init__(self, name, duration): self.name = name self.duration = duration def __str__(self): return '[%s](%dhour)' % (self.name, self.duration) def __repr__(self): return str(self) def __eq__(self, other): return self.name == other.name and self.duration == other.duration def __hash__(self): return hash((self.name, self.duration)) t1 = Training('Python', 14) t2 = t1 t3 = Training('Python', 14) s2.add(t1) s2.add(t1) s2.add(t2) print(s2) print('add t3') s2.add(t3) print(s2) ``` ## demo23_loop1 ```python= numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] sum = 0 for v in numbers: sum += v print(f'total={sum}') numbers2 = [6, -5, 3, -8, 4, -2, 5, -4, 11] for w in numbers2: if w < 0: numbers2.remove(w) print(numbers2) numbers3 = [6, -5, 3, -8, 4, -2, 5, -4, 11] for x in numbers3[:]: if x < 0: numbers3.insert(0, x) print(numbers3) ``` ```shell= conda info --envs pip list > all_packages cd root_directory conda create --name DS_Aug python=3.6 ``` ## demo1_version_check ```python= # pip install numpy pandas PIL matplotlib import numpy as np import pandas as pd import matplotlib import PIL print(np.__version__) # 1.12.1 print(pd.__version__) # 0.20.1 print(matplotlib.__version__) # 2.0.2 print(PIL.__version__) #4.1.1 ``` ## demo24_function1 ```python= def outer(num1): def inner_increment(num1): return num1 + 1 num2 = inner_increment(num1) print(num1, num2) outer(10) ``` ## demo25_recursion ```python= def factorial(number): if not isinstance(number, int): raise TypeError("Sorry, number must be integer") if not number > 0: raise ValueError("Sorry. number should be positive") def inner_factorial(number): if number <= 1: return 1 return number * inner_factorial(number - 1) return inner_factorial(number) print(factorial(-10)) ``` ## demo26_global1 ```python= x = 200 y = [200] def foo(): global x x *= 2 y[0] *= 2 p = 5 p *= 2 print(f'inside foo, x={x}, p={p},y={y}') foo() print(f"outside module, x={x},y={y}") ``` ## demo27_lambda1 ```python= import math def square_root(x): return math.sqrt(x) print(square_root(2)) def square_root2(x): return math.sqrt(x) print(square_root2(3)) square_root3 = lambda x: math.sqrt(x) print(square_root3(4)) ``` ## demo28_lambda2 ```python= def make_increment(n): return lambda x: x + n print(type(make_increment), type(make_increment(10)), type(make_increment(10)(10))) f1 = make_increment(10) print(f1(10), f1(20)) def make_tuple(p): return lambda x:(x, 'p'*p) f2 = make_tuple(5) print(f2(10), f2(20)) ``` ## demo29_lambda3 ```python= courses = [('poop', 10, 2), ('bdpy', 8, 5), ('pykt', 6, 7), ('aiocv', 9, 3)] courses.sort(key=lambda pair: pair[0]) print(f'sort by course name:{courses}') courses.sort(key=lambda pair: pair[1]) print(f'sort by class attendee:{courses}') courses.sort(key=lambda pair: pair[2]) print(f"sort by remote attendee:{courses}") ``` ## demo30_iterator1 ```python= class Counter(): def __init__(self, low, high): self.current = low self.high = high def __iter__(self): print("call __iter__") return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current -1 c1 = Counter(5,15) print(c1) # print(next(c1)) # print(next(c1)) # print(next(c1)) print([c for c in c1]) ``` ## demo31 ```python= def infinite_generator(start=0): while True: yield start start += 2 for num in infinite_generator(5): print(num, end=" ") if num > 20: break ``` ## demo29 ```python= courses = [('poop', 10, 2), ('bdpy', 8, 5), ('pykt', 6, 7), ('aiocv', 9, 3)] courses.sort(key=lambda pair: pair[0]) print(f'sort by course name:{courses}') courses.sort(key=lambda pair: pair[1]) print(f'sort by class attendee:{courses}') courses.sort(key=lambda pair: pair[2]) print(f"sort by remote attendee:{courses}") def sorter(item): return item[0] courses.sort(key=sorter) print(courses) ``` ## demo32 ``` def my_oreo(func): def wrapper(): print("upper side of the chocolate") func() print("lower side of the chocolate") return wrapper def add_filling(): print("butter_cream!") get_oreo1 = my_oreo(add_filling) get_oreo1() ``` ## demo33 ``` def my_oreo(func): def wrapper(): print("upper side of the chocolate") func() print("lower side of the chocolate") return wrapper def peanut(): print("peanut butter!") def regular(): print("butter_cream!") fillings = [peanut, peanut, peanut, regular, regular] for f in fillings: get_oreo1 = my_oreo(f) print(type(get_oreo1)) get_oreo1() ``` ## demo34 ```python= def my_oreo(func): def wrapper(): print("upper side of the chocolate") func() print("lower side of the chocolate") return wrapper @my_oreo def add_filling(): print("butter_cream!") add_filling() #get_oreo1 = my_oreo(add_filling) #print(type(get_oreo1)) #get_oreo1() ``` ## demo35 ```python= def my_oreo(func): def wrapper(x): print("upper side of the chocolate") func(x) print("lower side of the chocolate") return wrapper @my_oreo def add_filling(fill): print(f"{fill}_cream!") add_filling("vanilla_chocolate") ``` ## demo36 ```python= def my_oreo(func): def wrapper(*x): print("upper side of the chocolate") func(*x) print("lower side of the chocolate") return wrapper @my_oreo def add_filling(*fill): for f in fill: print(f"{f}_cream!") add_filling('cherry') add_filling('cherry', 'pineapple', 'mint_chocolate') add_filling() ``` ## demo37 ```python= import functools def my_oreo(func): @functools.wraps(func) def wrapper(x): print("upper side of the chocolate") print(f"filling={func(x)}") print("lower side of the chocolate") return wrapper @my_oreo def custom(fill): return "%s_cream!" % fill @my_oreo def traditional(fill): return "butter_cream!" cookie1 = custom('vanilla') cookie2 = traditional('whatever') print(repr(custom), repr(traditional)) print(repr(my_oreo)) ``` ## demo38 ```python= import functools import time def timer(func): def wrapper_timer(*args, **kwargs): startTime = time.perf_counter() value = func(*args, **kwargs) endTime = time.perf_counter() runTime = endTime - startTime print(f"Finished: {func.__name__} in {runTime:.4f} seconds") return value return wrapper_timer @timer def spend_time_to_calculate(num_times): for _ in range(num_times): p = sum([i ** 2 for i in range(10000)]) return p print(f"result = {spend_time_to_calculate(100)}") # def spend_time_to_calculate2(num_times): # for _ in range(num_times): # p = sum([i ** 2 for i in range(10000)]) # return p # print(f"previous run:{spend_time_to_calculate2(1)}") ``` ## demo39_process1 ```python= import multiprocessing import time def worker(): print('start working...') time.sleep(5) print('stop working...') return if __name__ == '__main__': jobs = [] for i in range(5): print(f'now execute part:{i}') p = multiprocessing.Process(target=worker) jobs.append(p) p.start() print(f"result={jobs}") ``` ## demo40_process2 ``` import multiprocessing import time def worker(num): print(f'{num}start working...') time.sleep(5) print(f'{num}stop working...') return if __name__ == '__main__': jobs = [] for i in range(5): print(f'now execute part:{i}') p = multiprocessing.Process(target=worker, args=(i,)) jobs.append(p) p.start() print(f"result={jobs}") time.sleep(1) print(f'result={jobs}') time.sleep(2) print(f'result={jobs}') time.sleep(3) print(f"result={jobs}") ``` ## demo41_process3 ```python= import multiprocessing import time def worker(): name = multiprocessing.current_process().name print(f'[{name}] starting') time.sleep(2) print(f"[{name}] finish") def service(): name = multiprocessing.current_process().name print(f'[{name}] starting') time.sleep(2) print(f"[{name}] finish") if __name__ == '__main__': print(f'in main process, name={multiprocessing.current_process().name}') s1 = multiprocessing.Process(name='db service', target=service) w1 = multiprocessing.Process(name='worker1', target=worker) w2 = multiprocessing.Process(target=worker) w3 = multiprocessing.Process(target=worker) s1.start() w1.start() w2.start() w3.start() ``` ## demo42_process4 ```python= import multiprocessing import time def service(): print(f'{multiprocessing.current_process().name} start') time.sleep(5) print(f'{multiprocessing.current_process().name} finish') if __name__ == '__main__': d1 = multiprocessing.Process(name='d1', target=service) d1.daemon = False d2 = multiprocessing.Process(name='d2', target=service) d2.daemon = True d1.start() d2.start() time.sleep(6) ```