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

Card value 'A', '2', '3', … , '10', 'J', 'Q', 'K' suit 'club', 'diamond', 'heart', 'spade' cards Card Card class Card: def __init__(self, value, suit): # ??? def __str__(self): # ??? def getScore(self): # ??? def sum(self, other): 10 : Class # ??? def __lt__(self, rhs): # ??? n = int(input()) cards = [] for i in range(n): value, suit = input().split() cards.append(Card(value, suit)) for i in range(n): print(cards[i].getScore()) print(\"----------\") for i in range(n-1): print(Card.sum(cards[i], cards[i+1])) print(\"----------\") cards.sort() for i in range(n): print(cards[i]) 144

Card Card getScore oA 1 o 2 10 2 10 o J, Q, K 10 sum mod o Card.sum(Card('7', 'club'), Card('2', 'heart')) 9 5 o Card.sum(Card('J', 'spade'), Card('5', 'diamond')) o 3 < 4 < 5 < … < 10 < J < Q < K < A < 2 o club < diamond < heart < spade o o n n 3n+1 n n-1 n 5 1 A spade 10 K heart 10 K club 7 7 diamond 2 2 spade ---------- 1 0 7 9 ---------- (7 diamond) (K club) (K heart) (A spade) (2 spade) 10 : Class 145

piggybank piggybank piggybank class piggybank: p1 = piggybank() def __init__(self): # self.coins print( float(p1) ) # 0.0 # key dict p1.add(0.25, 4) value # 25 4 print( float(p1) ) # 1.0 p1.add(0.50, 1) # 50 1 def add(self, v, n): print( float(p1) ) # 1.5 # n 100 p1.add(10, 1) # False # 10 1 # v float ( 5 5.0 ) print( float(p1) ) # 11.5 # v self.coins[v] = 0 print( p1 ) # self.coins[v] += n # {0.25:4, 0.5:1, 10.0:1} # True print(p1.add(10, 1)) # True print( float(p1) ) # 21.5 print(p1.add(1,94)) # False 100 print( float(p1) ) # 21.5 def __float__(self): 0.0 # # float def __str__(self): # # 146 10 : Class

__float__ float(p) p piggybank float p __str__ str(p) p piggybank p class piggybank cmd1 = input().split(';') cmd2 = input().split(';') p1 = piggybank(); p2 = piggybank() for c in cmd1: eval(c) for c in cmd2: eval(c) piggybank p1.add(1.11,2); print(float(p1), p1) 2.22 {1.11:2} print(float(p2), p2) 0.0 {} p1.add(0.25,1);p1.add(5,1);p1.add(0.25,2);p1.add(5.0,1) 10.75 {0.25:3, 5.0:2} print(float(p1), str(p1)) p1.add(0.25,1); print(p1.add(0.25,100)) False print(p1.add(0.25,99)); print(float(p1)) True 25.0 10 : Class 147

Intania 63 Programming

11 : Solutions to Exercises h = int(input()) import math m = int(input()) x,y = [float(e) for e in input().split()] s = int(input()) r = math.sqrt(x**2+y**2) total = 60*60*h + 60*m + s theta = math.atan2(y,x) print( total ) print(r,theta) import math x = float(input()) a,b,c,d,g = \\ y = 2 - x + 3/7*x**2 - 5/11*x**3 + \\ [float(e) for e in input().split()] math.log(x,10) avg = (a+b+c+d+g)/5 print(y) print(avg) a = float(input()) x=1 a,b,c = [e for e in input().split()] x = (x + a/x)/2 c = int(c) x = (x + a/x)/2 out = a + b + str(c) + (a + b) * c x = (x + a/x)/2 print(out) x = (x + a/x)/2 print(x) # ex. 3 4 1 --> median is 3 v1,v2,v3 = [float(e) \\ a,b,c = [int(e) for e in input().split()] if b <= a <= c or c <= a <= b : for e in input().split()] u1,u2,u3 = [float(e) \\ print(a) elif a <= b <= c or c <= b <= a : for e in input().split()] dotp = v1*u1 + v2*u2 + v3*u3 print(b) print(dotp) else : import math x1,y1,x2,y2 = \\ print(c) [float(e) for e in input().split()] x1,y1,r1 = [float(e) \\ d = math.sqrt((x1-x2)**2+(y1-y2)**2) for e in input().split()] print(d) import math x2,y2,r2 = [float(e) \\ r,theta = [float(e) \\ for e in input().split()] for e in input().split()] d = (x1-x2)**2 + (y1-y2)**2 x = r*math.cos(theta) sumr2 = (r1+r2)**2 y = r*math.sin(theta) if d < sumr2 : print(x, y) print('overlap') elif d == sumr2 : print('touch') else : print('free') 11 : Solutions to Exercises 149

x,y = [float(e) \\ c = int(input()) for e in input().split()] if c < 37 : if x == 0 and y == 0 : s = 'XS' print('At the origin') elif c < 41 : elif x == 0 : s = 'S' print('On y-axis') elif c < 43 : elif y == 0 : s = 'M' print('On x-axis') elif c < 46 : elif x > 0 and y > 0 : s = 'L' print('Quadrant I') else : elif x < 0 and y > 0 : s = 'XL' print('Quadrant II') print(s) elif x < 0 and y < 0 : k=1 print('Quadrant III') while 1/k*k == 1 : else : k += 1 print('Quadrant IV') print(k) k=1 a,b,c,d,e = [int(e) \\ p = 1.0 for e in input().split()] while (1-p) < 0.5 : if a <= b <= c <= d <= e : p *= (365-k)/365 print('True') k += 1 print(k) else : p = 0.0 print('False') for k in range(1,400000,4): # print( a <= b <= c <= d <= e ) p += 1/k p -= 1/(k+2) a,b,c,d = [int(e) \\ print(4*p) for e in input().split()] a,b = [int(e) for e in input().split()] s=0 mx = a for i in range(a,b): if b > mx : mx = b t=0 if c > mx : mx = c for j in range(i+1,b+1): if d > mx : mx = d t += (i+j) mn = a s += (-1)**i * t if b < mn : mn = b print(s) if c < mn : mn = c a,b = [int(e) for e in input().split()] if d < mn : mn = d s=0 s = (a+b+c+d) - mx - mn for i in range(a,b): print(s) for j in range(i+1,b+1): # s = (a+b+c+d)-max(a,b,c,d)-min(a,b,c,d) s += (-1)**i * (i+j) print(s) a = int(input()) x = int(round(a**(1/3),0)) if x**3 == a : print(x) else : print('Not Found') 150 11 : Solutions to Exercises

n = int(input()) h = input().strip() a = int(input()) d = '0123456789ABCDEF'.find(h) mn = mx = a if d >= 0 : c=0 if a < 0 : c = 1 print(d) for k in range(n-1): else : a = int(input()) print('invalid hex digit') if a > mx : mx = a t = input().strip() if a < mn : mn = a c=0 if a < 0 : c += 1 for e in t : print( (mx - mn), c ) n = int(input()) if e in '13579' : for x in range(1,n+1): c += 1 for y in range(x,n+1): print(c) for z in range(y,n+1): t = input().strip() t = x**2+y**2+z**2 c=0 w = int(round(t**(1/3),0)) for k in range(len(t)-1) : if w**3 == t: print(w,x,y,z) if t[k] in 'aeiou' and \\ t[k+1] in 'aeiou' : s = input().strip() t = '' c += 1 for e in s: print(c) b = input().strip() t += e*2 b = b[::-1] print(t) d=0 s = input().strip() for i in range(len(b)) : t = '' s=''+s+'' d += int(b[i])*2**i for i in range(1,len(s)-1) : print(d) t += s[i] file1 = open( input().strip() ) if s[i-1] != s[i] != s[i+1] : s = '' for line in file1 : t += s[i] if line[-1] != '\\n' : # \\n print(t) line = line + '\\n' s = input().strip() s = line + s # 151 if s == s[::-1] : file1.close() print(s[:-1]) # \\n print('Y') else: print('N') d,n = [int(e) for e in input().split()] t = \"0\"*n + str(d) t = t[-max(n,len(str(d))):] print(t) 11 : Solutions to Exercises

file1 = open( input().strip() ) n = int(input()) s = '' d = [] for line in file1 : for k in range(n): if len(line.strip()) > 0 : d.append( int(input()) ) if line[-1] != '\\n' d.sort() line = line + '\\n' t = [] s = line + s for e in d : file1.close() t.append(str(e)) out = open('reverse.txt', 'w') print(','.join(t)) out.write(s[:-1]) out.close() file1 = open( input().strip() ) file1 = open( input().strip() ) d = [] for line in file1 : for line in file1: a = line.find(\"<headline>\") d.append( int(line) ) if a >= 0 : file1.close() c = [] j = a+len(\"<headline>\") for e in d: b = line.find(\"</headline>\",j) print( line[j:b] ) c.append( d.count(e) ) file1.close() maxc = max(c) file1 = open( input().strip() ) out = [] file2 = open( input().strip() ) for k in range(len(d)): for line1 in file1 : line2 = file2.readline() if c[k]==maxc and d[k] not in out : if line1 != line2 : out.append(d[k]) print( False ) break for e in out : else : print(e) print( len(file2.readline()) == 0 ) file1.close() file1 = open( input().strip() ) file2.close() h = [] for line in file1 : readlines file1 = open( input().strip() ) a = line.find(\"<headline>\") file2 = open( input().strip() ) if a >= 0 : print( file1.readlines() == \\ j = a+len(\"<headline>\") file2.readlines() ) b = line.find(\"</headline>\",j) h.append( line[j:b] ) v1 = [float(e) for e in input().split()] file1.close() v2 = [float(e) for e in input().split()] h.sort() if len(v1) != len(v2) : for e in h : print(e) print( 'Error' ) else : file1 = open( input().strip() ) d = [] dotp = 0 for line in file1 : for k in range(len(v1)) : d.append( line.strip() ) dotp += v1[k]*v2[k] file1.close() print(dotp) for k in range(len(d)-1) : for i in range(len(d)-1) : if len(d[i]) > len(d[i+1]) or \\ len(d[i]) == len(d[i+1]) and \\ d[i] > d[i+1] : d[i],d[i+1] = d[i+1],d[i] for e in d : print(e) 152 11 : Solutions to Exercises

r,c = [int(e) for e in \\ d = [ e.count(c) for e in x ] input().split()] x = [e for e in x if e >= 0] m = [] x for k in range(r) : x[:] = [e for e in x if e >= 0] m.append( [int(e) for e in \\ input().split()] ) x y x y=x x if len(m[k]) != c : x m = [[]] y break y print( m ) # t = [ [1,2,3], [33], [3,3,3,4] ] infile = open(input().strip()) t = sum( [ sum(e) for e in x ] ) f = [] for line in infile : c = sum( [1 for e in input().split() \\ if int(e) < 0]) usernames = line.split() f.append( [usernames[0], \\ t = ''.join([e for e in input() \\ if 'a' <= e.lower() <= 'z']) usernames[1:]] ) infile.close() x = [float(e) for e in input().split()] print( f ) y = [float(e) for e in input().split()] #f z = [x[i]+y[i] for i in range(len(x))] nofollowers = [] for [username,followers] in f : f = [e for row in m for e in row] if len(followers) == 0 : x = [int(e) for e in input().split()] nofollowers.append( username ) x.sort() t = [x[i] for i in range(len(x)-1) \\ print( 'No followers :', \\ ','.join(nofollowers) ) if x[i] != x[i+1] ] t.append(x[-1]) n = int(input()) d = [] () for k in range(n) x = [int(e) for e in input().split()] t = [] s = input().strip() for e in x : d.append( [len(s),s] ) d.sort() if e not in t : for [c,s] in d : t.append(e) print(s) 153 11 : Solutions to Exercises

n = int(input()) x = int(input()) x = [j for i in range(2, n//2) \\ t = () while x > 0: for j in range(2*i, n, i)] x.sort() t = (x%10,) + t c = [x[i] for i in range(len(x)-1) \\ x //= 10 print(t) if x[i] != x[i+1] ] c.append(x[-1]) , int, n = int(input()) x = [j for i in range(2, n//2) \\ list, tuple x = input().strip() for j in range(2*i, n, i)] print(tuple([int(e) for e in x])) x.sort() c = [x[i] for i in range(len(x)-1) \\ x = input().strip() d = {} if x[i] != x[i+1] ] for e in x: c.append(x[-1]) p = [e for e in range(2,n) if e not in c] if e not in d: d[e] = 1 else: d[e] += 1 print(d) 1) dict key studentID, x = input().strip() value grade y = input().strip() 2) set set_x = set(x) studentID set_y = set(y) 3) dict key dept, print(set_x.intersection(set_y)) value set studentID 4) list phone def f1(a,b): 5) dict key TelNo, for i in range(b): print(a) value count def f2(a,b): x = int(input()) return [a]*b t = () for i in range(0,x,2): def g(m,b,n,c): if m==n and b!=c: return 1 # tuple t if m==n and b==c: return 2 x = (c-b)/(m-n) # tuple t y = m*x + b return (x,y) t += (i,) # t = t + (i,) print(t) def h(x): return [e for e in x if e%2==0] t = tuple([e for e in range(0,x,2)]) t = tuple(range(0,x,2)) def a(n): if n==0: return 1 if n==1: return -2 return a(n-2)*n 154 11 : Solutions to Exercises

def k(n): MAX = np.max(M,axis=0) if n==0: return 1 MIN = np.min(M,axis=0) if n==1: return 2 A = MAX-MIN if n%2==0: Y = (X[:,0]**2+X[:,1]**2)**0.5 x = k(n//2) k = int(input()) return x + x%10 C = np.zeros((k,k),int) return k(n//2-1)*(n//2) C[::2, 1::2] = C[1::2, ::2] = 1 k = int(input()) def s(i,k): C = np.zeros((k,k),int) if i>=k: return 0 C[::2, ::2] = C[1::2, 1::2] = 1 return k + t(i+1,k) C = (C*np.arange(1,k+1)).T # C*(np.arange(1,k+1).T) def t(j,k): if j>=k: return 0 def __init__(self, name, year, faculty): return j + s(j,k-1) self.name = name self.year = year def is_palindrome(s): self.faculty = faculty if len(s) <= 1: return True if s[0]!=s[-1]: return False def __str__(self): return is_palindrome(s[1:-1]) return self.name + \\ ' (year ' + str(self.year) + ') ' + \\ k = int(input()) self.faculty M[::k,::k] = 0 def __lt__(self, rhs): k = int(input()) if self.faculty != rhs.faculty: for i in range(M.shape[0]): return self.faculty < rhs.faculty if self.year != rhs.year: for j in range(M.shape[1]): return self.year < rhs.year if i%k==0 and j%k==0: return self.name < rhs.name M[i][j]*=2 155 k = int(input()) M = np.array([[2*M[i][j] if i%k==0 \\ and j%k==0 else M[i][j] \\ for j in range(M.shape[1])] \\ for i in range(M.shape[0])]) k = int(input()) N = np.zeros_like(M) N[::k,::k] = 1 M += M*N k = int(input()) M[::k,::k] *= 2 11 : Solutions to Exercises

def __init__(self, license, brand, color): def add_value(self, x): self.license = license self.value += x self.brand = brand self.color = color def enter(self, station): self.report = [] if self.station == '': self.station = station def __str__(self): return True return self.license + ' - ' \\ else: + self.color + ' ' + self.brand return False def __lt__(self, rhs): def leave(self, station): return self.license < rhs.license if self.station == '': return (self.value, -2) def add_report(self, new_report): price = Station.get_price \\ self.report.append(new_report) (self.station, station) if price > self.value: def total_payment(self): return (self.value, -1) return sum([r[2] for r in self.report]) else: self.value -= price def max_payment(self): self.station = '' if self.report == []: return [] return (self.value, 0) max_p = max([r[2] for r in self.report]) return [r for r in self.report \\ def __lt__(self, rhs): if r[2] == max_p] return self.value < rhs.value def add_book(self, book, n): for b in self.books: if b[0] == book: b[1] += n break else: self.books.append([book,n]) def delete_book(self, book): self.books = [[b,n] for [b,n] \\ in self.books if b != book] for k in range(len(self.books)): if self.books[k][0] == book: self.books.pop(k) break def get_total(self): return sum([b.price*n for \\ [b,n] in self.books]) def __lt__(self, rhs): return self.get_total() < \\ rhs.get_total() 156 11 : Solutions to Exercises

Appendix youtu.be/U2l1xgpVsuo?list=PL0ROnaCzUGB4ieaQndKybT9xyoq2n9 docs.python.org/3/tutorial/index.html, docs.python.org/3/library/index.html, docs.python.org/3 repl.it/languages/python3 openbookproject.net/thinkcs/python/english3 unexpected EOF while x = (1+(2**3) parsing s = 'hello EOL while scanning string literal invalid syntax : if while else if = if x = 1 : unexpected indent if a>0: a+=1 a+=2 Appendix 157

name 'x' is not defined x ZeroDivisionError: division print(x+1) by zero ImportError: No module pintt('cat') import import named 'maht' math.asin(0) print(5/0) AttributeError: module '3' 'math' has no attribute import maht 'arcsin' print(math.arcsin(0)) ValueError: math domain error print(math.asin(1000)) print(math.log(10,0)) invalid literal for int() with base 10 int() x = int('cat') could not convert string to float() x = float('cat') float Can't convert 'int' object int string to str implicitly print('cat'+3) sqrt() takes exactly one sqrt() argument (3 given) x = sqrt(4,9,16) ValueError: too many values a,b,c = 1,2,3,4,5 to unpack a,b,c = 1,2 ValueError: not enough values to unpack if 9 < '9': float TypeError: unorderable types: int() < str() int for i in range(2.5): 'float' object cannot be interpreted as an integer 158 Appendix

'int' object is not in in list, tuple, set, range, iterable int float index out of range for i in 5: string, dict indices must be integers x = 'cat'; print(x[100]) y = [1,2,3]; print(y[100]) x = 'cat'; print(x[2/1]) y = [1,2,3]; print(y['a']) FileNotFoundError: No such \\ \\\\ file or directory f = open('D:\\file.txt') f = open('D:\\\\file.txt') OSError: Invalid argument: dict key key 'D:\\x0cile.txt' dict KeyError d = {}; print(d[1]) key set s = {1,2,3}; s.remove(4) 'set' object has no ) s = {1,2,3}; s.delete(1) attribute 'delete' set delete ( error list, string, tuple dict TypeError: unhashable type list, set,ldiisctt, set, key list, set, dict dict return dict set d = {}; d[{1}] = 'cat' unsupported operand type(s) None for +: 'NoneType' and 'int' def func(x): x += 1 print(func(3)+1) return 'int' object is not a=3 callable b = a(5) RecursionError: maximum recursion depth exceeded def f(n): return n*f(n-1) Appendix 159

Intania 86 Intania 95 programming programming programming

import math x = int(input()) 1 math.exp(x): e x x,y,z = [float(e) for e in input().split()] math.cos(x): cosine x 3 math.sin(x): sine x int(x), float(x), str(x): math.sqrt(x): x x math.log(x,base): x base abs(n): n math.degrees(x): x round(f): f math.radians(x): x f 0.5 0.5 math.pi, math.e: round(f,d): f string s d range(start,stop [,step]) range(stop): s.lower(): s s.upper(): start stop-step s.find(sub): s s.find(sub,i): step ( start 0 step 1) s.count(sub): sub s -1 s.split(sep): enumerate(L): (index, element) s.strip(): sub s i s.join(L): ) L sub s s len(a): aa sep ( space import numpy as np numpy array s spaces max(a), min(a): aa L (L ) (numpy array np.max(a), np.min(a)) a key np.array(L): numpy array L type(a): a type([1,2]) <class 'list'> np.arange(start,stop,step): 1 list(), dict(), tuple(), set(): start,stop,step np.ones(shape): 1 shape shape list L np.zeros(shape): 0 L.append(e): e L np.identity(size): size x size e index L.insert(index,e): L 10 index L.pop(index): eL np.empty_like(a): a L.count(e): np.add(a,b), np.subtract(a,b), np.multiply(a,b), np.divide(a,b): dict D ab D.items(): (key, value) D np.dot(a,b): ab D.keys(): key key D.values(): D np.sin(a), np.cos(a), np.sqrt(a), np.abs(a): D.pop(k): value D D.update(D1): D key k sine, cosine, sqrt, abs a value D1 D np.max(a,axis), np.min(a,axis): / set S a axis np.argmax(a,axis), np.argmin(a,axis): S.add(e): e S / a axis S.difference(T): S-T a = np.array([ [2, 4, 6], [8, 10, 12] ]) S.discard(e): e Se S np.max(a) 12, np.argmax(a) 5 T S.intersection(T): S np.max(a,axis=0) array([8,10,12]) S.union(T): SUT np.argmax(a,axis=0) array([1,1,1]) S.issubset(T): ST np.argmax(a,axis=1) array([2,2]) S.issuperset(T): ST np.sum(), np.std(), np.mean(): np.max() S.pop(): S np.ndenumerate(a): (position,element) S.update(T): S = S U T a position

Find job opportuni es at jobs.exxonmobil.com


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