Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore python101_workbook_v1.0.2

python101_workbook_v1.0.2

Published by ณพิชญ์, 2022-06-26 10:15:49

Description: python101_workbook_v1.0.2

Search

Read the Text Version

Set dict key value key in string, tuple, list, set set_1 = set() 1, 2, 3 dict set_2 = {1, 2, 3} {'H','e','l','o'} set_3 = set('Hello') {'oh', 'no'} set_4 = set(['oh', 'no']) set_5 = set(set_2) set_2 key dict set_6 = set({1:2, 3:4}) {1,3} add(e) S = {1} S.add((2, 3)) set S.add('Hello') {1, (2, 3)} {1, (2, 3), 'Hello'} update(t) S = {1} S.update([2, 3]) t S.update('Hello') {1,2,3} S.update(6) {1,2,3,'H','e','l','o'} string, tuple, list, set error dict dict key s.update(t) for e in t : s.add(e) e in S S = {1, 2, 3, 'H', 'e', 'l', 'o'} e S x = 1 in S x = True y = 'h' in S y = False remove(e) discard(e) S = {1, 2, 3, 'H', 'e', 'l', 'o'} S.discard(1) {2, 3, 'H', 'e', 'l', 'o'} remove() error S.discard(4) error discard() S.remove('e') {2, 3, 'H', 'l', 'o'} S.remove('h') error 'h' 94 07 : Tuple, Dictionary and Set

set a = {1, 2, 3} b = {2, 3, 4} union() | c=a|b c = a.union(b) c = {1, 2, 3, 4} intersection() & c=a&b – c = a.intersection(b) c = {2, 3} difference() ^ c=a-b c = a.difference(b) c = {1} (A B) – (A B) c=b-a c = b.difference(a) c = {4} c = {1, 4} c=a^b issubset() a = {1, 2, 3} False issuperset() b = {1, 2} True a.issubset(b) True b.issubset(a) False a.issuperset(b) b.issuperset(a) 07 : Tuple, Dictionary and Set 95

len, sum, max, min, in x = sorted(q) q list, tuple, dict, set q list list tuple dict set x[i] t[i] (key, value) int, float, x[a:b:c] t[a:b:c] key str, tuple, bool for e in x for e in t key int, for e in s float, str, tuple, bool value key d[key] value value key for k in d for k in d.keys() for v in d.values() for k,v in d.items() key in, x.index(e) x.index(e) not in index e x index e x 96 07 : Tuple, Dictionary and Set

list tuple dict set x = [1,2,3,4] t = (1, 2, 3, 4) d = {'k1':1,'k2':2} s = {1, 2, 3, 4} x = list() t = (5,) d = dict() s = set() x = [] t = tuple() d = {} x = list(q) t = () s = set(q) t = tuple(q) q q for in q for in for in x = list(x1) d = dict(d1) s = set(s1) x1 list t = t1 d1 dict s1 set t1 tuple d = d1 s = s1 x = x1 tuple dict set list x.append(9) t=t + (9,) d['k3'] = 9 s.add(9) x.insert(1,9) t=t[:1]+(9,)+t[1:] d.update({'k3':9}) s.update({9}) x.pop(2) d.pop('k3') s.discard(99) x[2] = 7 t = t[:2] + t[3:] d['k3'] = 7 t=t[:2]+(7,)+t[3:] dict month = {'JAN':1, 'FEB':2, 'MAR':3} key value month[k] k value key num2en = {11:'eleven', 2:'two', 3:'three'} num2en[a] a set n = 13; c = set() for i in range(2, n//2) : for j in range(2*i, n, i) : intersection, c.add(j) # j add union, issubset set # c = {4, 6, 8, 9, 10, 12} 07 : Tuple, Dictionary and Set 97

tuple x, y, z z x,y list (x,y,z) tuple d = [ (1,1,3), (2,1,8), (3,1,2) ] t1 = t2 key z x,y tuple set for a,b,z in d : dict if x == a and y == b : print('z =', z) break else: print('Not Found') dict {(x,y):z} d={(1,1):3,(2,1):8,(3,1):2} z x,y if (x,y) in d : print('z =', d[(x,y)]) else : print('Not Found') dict d = {1:7, 2:8, 3:9} for k in d: print(k) for k in d.keys(): print(k) for v in d.values(): print(v) for k,v in d.items(): print(k,v) dict key d = {2:8, 1:8, 3:9} value for k in sorted(d.keys()): print(k,d[k]) for v in sorted(d.values()): print(v) dict d = {} n = int(input()) for i in range(n): k,v = input().split() d[k] = v value list dict d = {} set n = int(input()) for i in range(n): k,v = input().split() if k not in d: d[k] = [v] # d[k] d[k] = {v} else : d[k] d[k].add(v) d[k].append(v) # d[k] = [v] d[k] = list(v) v 98 07 : Tuple, Dictionary and Set

tuple d dict key value x = [(sum(scores),sid) for sid,scores in d.items()] t = [sid for sum_scores,sid in sorted(x)] print('\\n'.join(t)) dict key a value b c dict key value dict key b value c sid a cid dict stu dict key value stu = dict() for (sid,cids) in c.items() : for cid in cids : if cid not in stu : stu[cid] = {sid} else : stu[cid].add(sid) set dict c d = set() for cids in c.values() : d.update( cids ) a=b b set, dict A = {1:'one', 2:'two', 3:'three', 10:'ten'} list ab B=A B[4] = 'four' AB dict C = dict(A) AC dict a = set(b) a = dict(b) a = list(b) d.sort() d S = {3, 1, 2}; D = {'A':5, 'C':2, 'B':7} tuple, tuple, dict set S.sort() set sort sorted(d) d L = sorted(S) L = [1, 2, 3] dict, set list L = sorted(D) L = ['A', 'B', 'C'] L = sorted(D.values()) L = [2, 5, 7] 07 : Tuple, Dictionary and Set 99

tuple my_tuple = (1,) tuple my_tuple += (4,) (1, 4) my_tuple += 5 tuple my_tuple += (5) 5 5 not_a_tuple = (1) (5) tuple my_tuple[3] = 'B' tuple append, insert, add, pop, remove, discard my_tuple = my_tuple[:3] + ('B',) + my_tuple[4:] dict D = {'Name':'Tom', 'Age':39} print(D['Gender']) 'Name' 'Age' t c = dict() # key e t for e in t : c[e] += 1 for e in t : if e not in c : c[e] = 1 else : c[e] += 1 key dict list, dict my_dict = {} set my_dict[[1,2,3]] = 'list' [1,2,3] key dict D = {} D[1] = 1.00; D[2] = 2.00 for k in D.keys(): 1 # 122 key value value key key1 d dict for k,v in d.items() : for k in d.keys() : if k == key1 : if k == key1 : print('value =', v) print('value =', d[k]) break break else : else : print('Not found') print('Not found') if key1 in d : print( 'value =', d[key1] ) else : print('Not found') 100 07 : Tuple, Dictionary and Set

dict set x = {} dict set S = {1, 2} print(S) {1, 2} {2, 1} set_1 = {'Hello'} {'Hello'} set_2 = set('Hello') {'H', 'e', 'l', 'o'} set_3 = set(['Hello', 'World']) {'Hello', 'World'} s = set(q) s = set() for e in q : s.add(e) list, dict set set my_set = {1} my_set.add((1,2)) my_set.add([2,3,4]) set a = {1, 2, 3} b = {2, 3, 4} c = a.union(b) c = {1, 2, 3, 4} a = {1, 2, 3} b = {2, 3, 4} set A = {'one', 'two', 'three'} set for i in range(len(A)) : print( A[i] ) for...in for e in A : print( e ) Problem Code x 07 : Tuple, Dictionary and Set 101

Problem Code 10 0 x (0, 2, 4, 6, 8) x 12803 x x (1, 2, 8, 0, 3) book x x {'b':1, 'k':1, 'o':2} xy xy book bank {'b', 'k'} 102 07 : Tuple, Dictionary and Set

3 Jim Tom Tom Engineering Jim Pam Tom Pam Arts Jim Engineering Engineering 5 Tom Engineering Pam Arts Jim Engineering Tom Arts Jenny Science Engineering Arts { 'Engineering' : {'Tom', 'Jim'}, 'Arts' : {'Pam', 'Tom'}, 'Science' : {'Jenny'} } 07 : Tuple, Dictionary and Set 103

n = int(input()) n fac2name fac2name = {} dict n for i in range(n): set (key, value) name,fac = input().split() key dict fac2name[fac] = {name} value n = int(input()) add value dict fac2name = {} add dict for i in range(n): dict name,fac = input().split() key set fac2name[fac].add(name) n = int(input()) add fac2name = {} for i in range(n): list name,fac = input().split() if fac in fac2name: ask_fac fac2name[fac].add(name) dict else: 07 : Tuple, Dictionary and Set fac2name[fac] = {name} ask_fac = input().split() ans_set = {} ans_set = set() 104

for f in ask_fac: ans_set union ans_set.union(fac2name[f]) union for f in ask_fac: ans_set ans_set = ans_set.union(fac2name[f]) union for f in ask_fac: ans_set if f in fac2name: ans_set = ans_set.union(fac2name[f]) dict print(' '.join(ans_set.sort())) ans_set set print(' '.join(list(ans_set).sort())) sort() ans_list = list(ans_set) list sort() ans_list.sort() list(ans_sort).sort() print(' '.join(ans_list)) print(' '.join(sorted(ans_set))) join list sort join sorted sorted set join 07 : Tuple, Dictionary and Set 105

union n intersection n n union intersect 3 5 1212312121 2 23 9 2543 0 6 100 1000 3 101 123 3 200 201 -1 -2 -3 6 -1 0 1 -1 1 0 0 -1 1 0 1 -1 1 -1 0 1 0 -1 106 07 : Tuple, Dictionary and Set

10 wr Adjective good 5 Noun goose wrap Verb Verb wrap write Verb Verb write wrinkle Noun Noun wrinkle wreck Noun Noun wreck wrangler Noun Noun wrangler go Noun hall 2 Adjective happy good Adjective Noun hobby goose Noun 6 good Adjective Verb wrap Verb write Noun hall Noun hobby Noun goose 07 : Tuple, Dictionary and Set 107

001 c001 c002 c003 213 002 c002 c003 c004 011 003 c003 c005 -1 c002 c003 5931111121 2110101 2109101 5932222221 2109101 -1 2110101 5500101 { 07 : Tuple, Dictionary and Set 'c001':{'001'}, 'c002':{'001', '002'}, 'c003':{'001', '002', '003'}, 'c004':{'002'}, 'c005':{'003'} } 108

08 : Function and Recursion return def average3(x,y,z): s = x+y+z return s/3 return return tuple return (answer1, answer2) return return return None None 'None' int, float, string, boolean list, dict, set 08 : Function and Recursion 109

def factorial(n): if n < 2: return 1 return n * factorial(n-1) def f(n): if n == 0: return 0 if 1 <= n <= 2: return 1 return f(n-1) + f(n-2) print(median(3,1,2)) median def median(x,y,z): return (x+y+z)-min(x,y,z)-max(x,y,z) def average(x,y): average return (x+y)/2 def average(x,y,z): average return (x+y+z)/3 print(average(1,2,3)) print(average(4,5)) average = 0 average print(average(1,2,3)) average 110 08 : Function and Recursion

list, set def sum_double(x): for i in range(len(x)): dict x[i] *= 2 # x x return sum(x) def f(x) : ... y = [1, 2, 3] 12 #x print(sum_double(y)) [2, 4, 6] x.append(e) print(y) x[i] = e x[:] = [0,0,0] y x.pop(0) ... def double(x) : x *= 2 f(y) def sum_double(x): def f(x) : x = [2*e for e in x] # x ... return sum(x) #x x = [1,2,3] y a=8 ... double(a) f(y) print(a) 8 16 return y = [1, 2, 3] () print(sum_double(y)) 12 print(y) [1, 2, 3] def square(x): None x = x**2 def clip(x): x 255 None if x > 255 : return 255 def read_next_positive_int(): n = int(input()) while n <= 0 : n = int(input()) return n a = read_next_positive_int () a = read_next_positive_int() 08 : Function and Recursion 111

def f(n): n range f g=1 for k in range(n) : g = 1 + 1/(1+g) return g a = int(input()) b = f(a/2) float c = f(10*a) def factorial(n): return n * factorial(n-1) def factorial(n): return n * factorial(n-1) if n == 0: return 1 def f(n): if n == 0: return 1 return f(n-1) + f(n-1)**2 def f(n): if n == 0: return 1 x = f(n-1) return x + x**2 f1 a b a b f2 b a b a 112 08 : Function and Recursion

g mbn c tuple y = mx+b y = nx+c (x,y) h 1 2 x x x k(2n) = k(n)+(k(n)%10) if n > 0 k(2n+1) = k(n-1)*n if n > 0 k(0) = 1 k(1) = 2 is_palindrome s s True s 113 False 08 : Function and Recursion

Function Refactoring AB is_leap_year(y) True y False y day_of_year(d,m,y) dmy y days_in_year(y) A d1 m1 y1 B B d2 m2 y2 A AB AB 1 1 2018 731 1 1 2020 76 25 12 1999 9 3 2000 114 08 : Function and Recursion

d1,m1,y1 = [int(e) for e in input().split()] d2,m2,y2 = [int(e) for e in input().split()] #A # D = [31,28,31,30,31,30,31,31,30,31,30,31] if y1%4==0 and (y1%100!=0 or y1%400==0): D[1] += 1 A=0 for i in range(m1-1): A += D[i] A += d1 #B # D = [31,28,31,30,31,30,31,31,30,31,30,31] if y2%4==0 and (y2%100!=0 or y2%400==0): D[1] += 1 B=0 for i in range(m2-1): B += D[i] B += d2 #A B C=0 for i in range(y1+1,y2): # if i%4==0 and (i%100!=0 or i%400==0): # C += 366 else: C += 365 print( ?? ) # ( A) – ( A) + 1 + ( )+( B) 08 : Function and Recursion 115

is_leap_year is_leap_year def is_leap_year(y): False True if y%4==0 and (y%100!=0 or y%400==0): return True else else: return True return False return False def is_leap_year(y): if y%4==0 and (y%100!=0 or y%400==0): return True return False def is_leap_year(y): True False return y%4==0 and (y%100!=0 or y%400==0) day_of_year def day_of_year(d,m,y): d1,m1,y1 d,m,y D = [31,28,31,30,31,30,31,31,30,31,30,31] return A if y%4==0 and (y%100!=0 or y%400==0): D[1] += 1 A=0 for i in range(m-1) A += D[i] A += d def day_of_year(d,m,y): D = [31,28,31,30,31,30,31,31,30,31,30,31] if y%4==0 and (y%100!=0 or y%400==0): D[1] += 1 A=0 for i in range(m-1) A += D[i] A += d return A 116 08 : Function and Recursion

def day_of_year(d,m,y): is_leap_year D = [31,28,31,30,31,30,31,31,30,31,30,31] if is_leap_year(y): is_leap_year D[1] += 1 A=0 day_of_year for i in range(m-1) A += D[i] y A += d return A days_in_year(y) def days_in_year(y): if y%4==0 and (y%100!=0 or y%400==0): return 366 else: return 365 def days_in_year(y): if is_leap_year(y): return 366 else: return 365 def days_in_year(y): return day_of_year(31,12,y) d1,m1,y1 = [int(e) for e in input().split()] d2,m2,y2 = [int(e) for e in input().split()] A = day_of_year(d1,m1,y1) B = day_of_year(d2,m2,y2) C=0 for i in range(y1+1,y2): C += days_in_year(i) print(days_in_year(y1) - A + 1 + C + B) 08 : Function and Recursion 117

Four Functions def make_int_list(x): int list #x [12, 34, 5] # x = '12 34 5' def is_odd(e): #e def odd_list(alist): # list alist # alist = [10, 11, 13, 24, 25] [11, 13, 25] def sum_square(alist): alist # (1*1 + 3*3 + 4*4) = 26 # alist = [1,3,4] exec(input().strip()) # print(make_int_list('1 2 3 4 5')) [1, 2, 3, 4, 5] print(is_odd(2222)) False print(odd_list([1,2,3,4,5,6,7])) [1, 3, 5, 7] print(sum_square([1,1,2,3])) 15 118 08 : Function and Recursion

Recursive C(n,k) 6 15 2 10 45 8 00 1 30 7 10 1 10 08 : Function and Recursion 119

Recursive SumList sumlist x x sumlist(x) xx if type(x) == list def sumlist( x ): # ??? print(eval(input().strip())) # do not remove this line sumlist([[],[[]]]) 0 sumlist([1,1,2,2]) 6 sumlist([1,[1],[2,[2],0,[0,0]]]) 6 sumlist([0,[1,[2,[3,[4,5],6],7],8],[9,10]]) 55 120 08 : Function and Recursion

09 : NumPy import numpy as np n ndarray int float 1 2 L np.array(L) M M.shape [1 0 2 3 -1] np.array([1,0,2,3,-1]) [[2 3] np.array([[2,3],[4,1],[7,5]]) np.ones((3,2),int) [[0. 0. 0.] np.zeros((2,3)) [4 1] np.identity(3) [0. 0. 0.]] [7 5]] [[1 1] [[1 0 0 0] np.identity(4,int) [1 1] [0 1 0 0] [1 1]] [0 0 1 0] [[1. 0. 0.] [0 0 0 1]] [0. 1. 0.] [0. 0. 1.]] np.zeros_like(x,int) np.ones_like(y,float) x int float y int float x y np.arange(8.0,4.0,-1.0) 0 int 1.0 np.arange(8,4,-1,float) np.arange(2.3,2.5,0.03) [4 5 6 7 8 9] np.arange(4,10) [8. 7. 6. 5.] [2.3 2.33 2.36 2.39 2.42 2.45 2.48] 09 : NumPy 121

A+B np.array([1,2,3]) + np.array([1,1,1]) np.array([2,3,4]) 1/(np.array([1,2,4])) np.array([1.0, 0.5, 0.25]) A.shape = (2,3), B.shape = (3,) 3 BA [[1 2 3] + [9 8 7] [[1 2 3] + [[9 8 7] = [[10 10 10] [4 5 6]] [4 5 6]] [9 8 7]] [13 13 13]] o A.shape = (2,3), B.shape = (2,1) B (2,3) A o A.shape = (1,3), B.shape = (2,1) AB (2,3) [[1 2 3]] + [[6] [[1 2 3]] + [[7]] [[1 2 3] + [[6 6 6] = [[ 7 8 9] 9 10]] o A.shape = (2,3), B.shape = (1,) [1 2 3]] [7 7 7]] [ 8 [[1 2 3] + 9 [4 5 6]] BB (1,)) o A.shape = (3,5), B.shape = (5,1) [[1 2 3] + [[9 9 9] = [[10 11 12] [4 5 6]] [9 9 9]] [13 14 15]] B1 o1 o V[k] k o V[a:b:c] o V[k] = 99 a:b:c o V[a:b:c] = d V a:b:c V d int, float V [0 0 1 1 0] V [3 0 3 1 3] d [9 0 9 1 9] o V = np.zeros(5,int) [8 0 8 1 8] o V[2:4] = 1 o V[::2] = 3 o V[::2] = [9] o V[::2] = [8,8,8] o V[1:5] = [1,2] o V[7:7] = [1,2] 122 09 : NumPy

o2 1 1 2 o M[r,c] rc o M[r,:] M[r] r o M[:,c] c o M[r1:r2,:] M[r1:r2] r1 r2-1 o M[:,c1:c2] c1 c2-1 o M[r1:r2,c1:c2] r1 r2-1 c1 c2-1 o M[r1:r2:a,c1:c2:b] r1:r2:a, c1:c2:b o M = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) M[1:3] np.array([[5,6,7,8],[9,10,11,12]]) M[1:2, 1:3] np.array([[6,7]]) M[:, 2] np.array([3,7,11]) M[1:, :2] np.array([[5,6],[9,10]]) M[0:3:2] np.array([[1,2,3,4],[9,10,11,12]]) M[0:3:2, 1:4:2] np.array([[2,4],[10,12]]) M[::-1] np.array([[9,10,11,12],[5,6,7,8],[1,2,3,4]]) o M[2:4, 1:4] = [[-1, 1, -1], [-1, 1, -1]] M M[2:4, 1:4] = [-1, 1, -1] 0 o M[:, 0] = [1, 2, 3, 4] o M[::2, ::3] = 0 dot x.dot(y) np.dot(x,y) dot dot product dot x = np.array([ 1, 2, 3, 4]) x = np.array([[1,2],[3,4],[5,6]]) x.shape (3,2) (2,1) y = np.array([ 0, -1, 1, 2]) y = np.array([[-2],[3]]) y.shape (1,2) (2,) x.dot(y) y.dot(x) z = np.array([[-2,3]]) z.shape 1*0 + 2*(-1) + 3*1 + 4*2 = 9 w = np.array([-2,3]) w.shape x.dot(y) np.array([[4],[6],[8]]) (3,2) (2,1) (3,1) (3,2) y.dot(x) (2,1) (1,2) x.dot(z) (3,2) (3,) x.dot(w) np.array([4,6,8]) (3,2) (2,) 09 : NumPy 123

(M = np.array([[1,2,3,4],[5,6,7,8]])) sum, max, min, mean, std, argmax, argmin np.sum(M) np.sum(M) 36 np.sum(M,axis=0) np.sum(M,axis=0) np.array([6,8,10,12]) np.sum(M,axis=1) np.sum(M,axis=1) np.array([10,26]) M.T M.T np.array([[1,5],[2,6],[3,7],[4,8]]) M > 3 array([[False,False,False,True],[True,True,True,True]]) np.sum np.sum(M > 3) 5 M[M%2==0] np.array([2,4,6,8]) import numpy import numpy as np import numpy np int float x = np.zeros((3,4)) # float x = np.zeros((3,4),int) # int x = np.zeros_like(y) # y float int x = np.array([1,2,3],int) x[0] = 4.8 #x np.array([4,2,3]) np.array np.ndarray 4×5 a = np.array((4,5)) # [4,5] 2x3 [2,3] # a = np.ndarray([2,3]) x = np.array([1,2,3]) 13 12 y = np.array([[1,2,3]]) 21 3 x.shape (3,) y.shape (1,3) x.T x x.T.shape (3,) y.T 3 1 y.T.shape (3,1) print(x.dot(x.T)) 14 print(x.T.dot(x)) 14 print(y.dot(y.T)) array([[14]]) print(y.T.dot(y)) np.array([[1,2,3],[2,4,6],[3,6,9]]) 124 09 : NumPy

x = np.array([[1,2,3],[4,5,6]]) # [[3,4,5],[6,7,8]] y = x+2 # [[2,4,6],[5,7,9]] y = x+[1,2,3] # [[2,4,6],[5,7,9]] y = x+np.array([1,2,3]) # [[2,4,6],[5,7,9]] y = x+np.array([[1,2,3]]) # [[2,4,6],[5,7,9]] y = x+np.array([[1],[2],[3]]).T # y = x+np.array([[1],[2],[3]]) # y = x+np.array([[1,2,3]]).T # [[2,3,4],[6,7,8]] y = x+np.array([[1,2]]).T Problem Code : 2M k k 1 k M : 2M k 1 M 2 2M M = np.array([[3,2],[5,6],[7,1]]) A np.array([4,5]) 4 7-3 5 6-1) X X = np.array([[3,4],[5,12],[24,7]]) Y X Y array([5.,13.,25.]) :1 k k×k 0 1 0 k=5 C = np.array([[0,1,0,1,0] [1,0,1,0,1] [0,1,0,1,0] [1,0,1,0,1] [0,1,0,1,0]]) 09 : NumPy 125

Problem Code :1 k k×k 1 1 k=5 C = np.array([[1,0,1,0,1] [0,2,0,2,0] [3,0,3,0,3] [0,4,0,4,0] [5,0,5,0,5]]) Weighted Score 11.25 15.0 n 10.75 n 12.0 17.0 n 18.0 4 09 : NumPy 10 15 10 20 5 15 14 8 7 12 12 12 0.5 0.25 0.25 2 10 30 20 20 10 30 0.6 0.3 0.1 126

n = int(input()) S S = [] W for i in range(n): S = [[10,30,20],[20,10,30]] S.append([int(e) for e in input().split()]) W = [0.6,0.3,0.1] W = [float(e) for e in input().split()] for i in range(n): for score = [S[i][j]*W[j] for j in range(3)] numpy print(sum(score)) n = int(input()) SW numpy array S = [] for i in range(n): 7 S.append([int(e) for e in input().split()]) W = [float(e) for e in input().split()] NameError: name 'np' is not defined score = [sum([S[i][j]*W[j] \\ np for j in range(3)]) \\ import numpy as np for i in range(n)] for i in score: numpy print(i) n = int(input()) S = [] for i in range(n): S.append([int(e) for e in input().split()]) W = [float(e) for e in input().split()] S = np.array(S) W = np.array(W) for i in range(n): print(sum(S[i]*W)) import numpy as np n = int(input()) S = [] for i in range(n): S.append([int(e) for e in input().split()]) W = [float(e) for e in input().split()] S = np.array(S) W = np.array(W) for i in range(n): print(sum(S[i]*W)) 09 : NumPy 127

import numpy as np S *= W numpy n = int(input()) W S = [] S for i in range(n): 28 9 S.append([int(e) for e in input().split()]) 9 W = [float(e) for e in input().split()] S = np.array(S) axis W = np.array(W) S *= W axis = 1 total_score = np.sum(S, axis = 0) for i in total_score: 10 14 print(i) 10 import numpy as np 12 n = int(input()) S = [] S *= W for i in range(n): S.append([int(e) for e in input().split()]) W = [float(e) for e in input().split()] S = np.array(S) W = np.array(W) S *= W total_score = np.sum(S, axis = 1) for i in total_score: print(i) import numpy as np T = S*W n = int(input()) S = [] 11.25 for i in range(n): 15.0 10.75 S.append([int(e) for e in input().split()]) 12.0 W = [float(e) for e in input().split()] S = np.array(S) S.dot(W) W = np.array(W) T = S*W total_score = np.sum(T, axis = 1) for i in total_score: print(i) import numpy as np n = int(input()) S = [] for i in range(n): S.append([int(e) for e in input().split()]) W = [float(e) for e in input().split()] S = np.array(S) W = np.array(W) for i in S.dot(W): print(i) 128 09 : NumPy

Input ( ) Output ( ) 50 30 40 20 Thu 172 20 50 10 15 20 5700 5400 3480 5940 4950 30 40 20 65 35 75 30 42 70 45 40 25 35 22 55 x= rentalrates = numpy array x sales = numpy array k = 0,1,2,3 k sales[k,] = list k totalsales = sales d = totalsales d=0 1 4 d ('Mon', 'Tue', 'Wed', 'Thu', 'Fri') totalsales[d] salesvalues = rentalrates dot sales) salesvalues 09 : NumPy 129

BMI read_height_weight() numpy array read_height_weight() 4 array([[160, 60], 160 60 [155, 62], 155 62 [170, 54], 170 54 [180, 55]]) 180 55 cm_to_m(x) cal_bmi(hw) cm_to_m(x) array array cal_bmi(hw) array([160, 155, 170, 180]) array([1.6,1.55,1.7,1.8]) array n array bmi array([[160, 60], array([23.4375, 25.80645161, [155, 62], 18.68512111, 16.97530864]) [170, 54], [180, 55]]) bmi avg_bmi bmi 18.5 130 09 : NumPy

import numpy as np def read_height_weight(): list_hw = [] for k in range(int(input())) : h,w = input().split() list_hw.append((int(h),int(w))) return np.array(list_hw) def cm_to_m(x): # ??? def cal_bmi(hw): # ??? def main(): hw = read_height_weight() bmi = cal_bmi(hw) avg_bmi = ______________________________________ count_underweight = ____________________________ print('average bmi =', avg_bmi) print('#bmi < 18.5 =', count_underweight) exec(input().strip()) Input ( ) Output ( ) x=np.array([160,150,140]); print(cm_to_m(x)); print(x) [ 1.6 1.5 1.4] [160 150 140] d=np.array([[100,30],[120,36]]); print(cal_bmi(d)) [ 30. 25.] main() average bmi = 21.2260953405 4 #bmi < 18.5 = 1 160 60 155 62 170 54 180 55 09 : NumPy 131

I fib(n,k) Fn % k numpy %k % k numpy import numpy as np def fib(n,k): # ??? n,k = [int(e) for e in input().split()] print( fib(n,k) ) n k (0 ) Fn % k 0 10 0 2 10 1 89 10 9 11111 111 55 1234567890 1234 162 10000000000000 999 600 132 09 : NumPy

10 : Class b1 = Book(...) b1 Book Book self Book self. __init__ __str__ self __lt__ Book str print < sort update_price get_common_keywords class Book: def __init__(self, title, price, keywords): self.title = title; self.price = price; self.keywords = set(keywords) def __lt__(self, rhs): if self.price != rhs.price: return self.price < rhs.price else: return self.title < rhs.title def __str__(self): return self.title + ' ($' + str(self.price) + ')' def update_price(self, new_price): self.price = new_price def get_common_keywords(self, other): return self.keywords & other.keywords b1 = Book('Python', 99, ['code','computer']) # using __init__ b2 = Book('Calculus', 199, ['maths']) b3 = Book('Physics', 99, ['science','maths']) b1.update_price(199) # {'maths'} print(Book.get_common_keywords(b2,b3)) # using __lt__ & __str__ if b3 < b2: print(b1) # using __lt__ books = [b1,b2,b3] # using __str__ books.sort() print(books[0],',',books[1],',',books[2]) # 'Physics ($99) , Calculus ($199) , Python ($199)' 10 : Class 133

o Book.get_common_keywords(b2,b3) __lt__ o b2.get_common_keywords(b3) b3 other b2 self Book.__str__(b1) b1.__str__() str(b1) print(str(b1)) print(b1) Book.__lt__(b1,b2) b1.__lt__(b2) b1 < b2 Book books.sort() self class A: self def __init__(self, x, y): self. d = dict() # self.d = dict() d[x] = y # self.d[x] = y def total(): # def total(self): return sum(d.values()) # return sum(self.d.values()) class B: def __init__(self, b): self.b = b b1 = B(10) # b1, b2 b2 = b1 #5 b2.b = 5 print(b1.b) class C: def __init__(self, c): self.c = c def double(self): # self.c *= 2 # double(c1) c1.double() # C.double(c1) # 134 10 : Class

class Nisit: def __init__(self, name, year, faculty): # n = Nisit('Krit', 4, 'Engineering') def __str__(self): 'Krit (year 4) Engineering' # def __lt__(self, rhs): # # # Nisit('Krit', 4, 'Engineering') < Nisit('Boy', 3, 'Science') # Nisit('Prim', 2, 'Engineering') < Nisit('Krit', 4, 'Engineering') # Nisit('Joey', 2, 'Engineering') < Nisit('Prim', 2, 'Engineering') 10 : Class 135

class Car: def __init__(self, license, brand, color): # c = Car('AA1234', 'Honda', 'White') # report def __str__(self): 'AA1234 – White Honda' # def __lt__(self, rhs): # def add_report(self, new_report): # # new_report tuple # c.add_report( ('25 May 2017', 'change tires', 1500) ) def total_payment(self): # def max_payment(self): # # 136 10 : Class

class Book class ShoppingCart class ShoppingCart: [[b1,2],[b3,7]] def __init__(self, id): self.id = id n self.books = [] # books [book, n] books def add_book(self, book, n): n # book # add_book(b1,3) books = [[b1,5]] # # books = [[b1,2]] def delete_book(self, book): # book # book def get_total(self): # def __lt__(self, rhs): # 10 : Class 137

Station BTScard Station BTScard add_value, enter, leave __lt__ BTScard s1 = Station(1,'Siam'); s2 = Station(3,'Mo Chit'); s3 = Station(5,'Asok') c1 = BTScard(123, 5); c2 = BTScard(999, 10) # -------------------------------------------------------------- c1.add_value(100) # c1 105 p = c1.enter(s1) # p = True p = c1.enter(s3) # p = False p = c1.leave(s2) # c1 95 p = (95, 0) # -------------------------------------------------------------- p = c2.enter(s3) # p = True p = c2.leave(s1) # c2 10 p = (10, -1) c2.add_value(50) # c2 60 p = c2.leave(s1) # c2 40 p = (40, 0) p = c2.leave(s2) # p = (40, -2) p = c2.enter(s2) # p = True p = c1 < c2 # p = False class Station: # (id) (name) def __init__(self, id, name): # 1 self.sid = int(id) # self.name = name # def get_price(self, other): # self other return abs(self.sid - other.sid)*5 # ------------------------------------------------------------------ class BTScard: # (id) (value) def __init__(self, id, value): # self.cid = id # self.station self.value = value # self.station = '' # def __str__(self): return '('+str(self.cid)+','+str(self.value)+')' def add_value(self, x): # x return 138 10 : Class

def enter(self, station): station return True # return False # # def leave(self, station): -2 -1 # return tuple 0 # return tuple # # # return tuple def __lt__(self, rhs): # 10 : Class 139

Bus people fare __init__ k 0 __str__ k0 __lt__ people_in new_fare people_out change_fare # b1 has 10 people with fare = 5 # b2 has 8 people with fare = 7 b1 = Bus(10, 5) # b1 < b2 is True (10*5 < 8*7) b2 = Bus( 8, 7) this bus has 10 people with fare = 5 if b1 < b2: # b1 has 13 people with fare = 5 # b1 has 7 people with fare = 5 print(b1) # b1 has 7 people with fare = 12 else: this bus has 7 people with fare = 12 print(b2) b1.people_in(3) b1.people_out(6) b1.change_fare(12) print(b1) class Bus: self def __init__(people, fare): people_in people_out people = people change_fare fare = fare people_out def __str__(): return 'this bus has ' + str(people) \\ + ' people with fare = ' + str(fare) def __lt__(rhs): return people*fare < \\ rhs.people*rhs.fare def people_in(k): return people += k def people_out(k): return people -= k def change_fare(new_fare): return fare = new_fare 140 10 : Class

class Bus: self.people = max(0,self.people-k) def __init__(self, people, fare): self.people = people Bus self.fare = fare change_fare def __str__(self): self.fare return 'this bus has ' + \\ str(self.people) + \\ ' people with fare = ' + \\ str(self.fare) def __lt__(self, rhs): return self.people*self.fare < \\ rhs.people*rhs.fare def people_in(self, k): self.people += k def people_out(self, k): self.people = max(0,self.people-k) def change_fare(self, new_fare): self.fare = new_fare class Bus: def __init__(self, people, fare): self.fare = fare self.total = people*fare def __str__(self): return 'this bus has ' + \\ str(self.total//self.fare) + \\ ' people with fare = ' + \\ str(self.fare) def __lt__(self, rhs): return self.total < rhs.total def people_in(self, k): self.total += self.fare*k def people_out(self, k): self.total = max(0,self.total- \\ self.fare*k) def change_fare(self, new_fare): self.total = \\ self.total//self.fare*new_fare self.fare = new_fare 10 : Class 141

def gcd(x,y): 10 : Class if x%y == 0: return y return gcd(y,x%y) class Fraction: def __init__(self,a,b): self.numerator = ___________________ self.denominator = ___________________ def __str__(self): # ??? def simplify(self): g = gcd(self.numerator,self.denominator) return Fraction(self.numerator//g,self.denominator//g) def add(self,other): # ??? def multiply(self,other): ans_numer = self.numerator * other.numerator ans_denom = self.denominator * other.denominator return Fraction(ans_numer,ans_denom).simplify() a,b,c,d = [int(e) for e in input().split()] fraction1 = ____________________ fraction2 = ____________________ print(fraction1.add(fraction2)) print(Fraction.multiply(fraction1,fraction2)) simplify 142

abcd a/b c/d 1737 4/7 1213 3/49 1838 5/6 2312 1/6 1/2 3/64 7/6 1/3 10 : Class 143


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook