# python營隊 :::info 本文採用[CC-BY-NC](https://creativecommons.org/licenses/by-nc/4.0/)授權 投影片及內文的外部索引資料之版權屬原著作人所有 ::: [上課投影片 Day1](https://drive.google.com/open?id=1sfl7zr4k3RXLn6ayLKDef7XpPD_8qU08) [上課投影片 Day2](https://drive.google.com/open?id=12GlMG46hCoEP4-Q9INL9cQC2zbV6H-mv) [上課投影片 Day3](https://drive.google.com/open?id=12qhj90a2ZRoFw-WABwguOHBcNaFxulen) ## 變數轉型 - int():轉成整數 - float():轉成浮點數 - str():轉成字串 ## 變數指派 - 用=把右邊的運算結果存到左邊的變數裡 - 變數名稱要英文字母開頭 ## python內建指令 - 用```%reset```來清除目前暫存區的變數 - ```print()```:將變數印出來 - ```s = input("提示字串")```:使用者輸入 ## list相關連結 - [runoob.com中文版說明](http://www.runoob.com/python/python-lists.html) - [英文版說明](https://docs.python.org/3/tutorial/datastructures.html) ## dict相關連結 - [中文版](http://www.runoob.com/python/python-dictionary.html) ## for範例程式 - 1加到100 ```python= s=0 for i in range(100): s=s+i+1 print(s) ``` - 列出是2或3的倍數但不是6的倍數的所有整數 ```python= a = input("Please input an int:") a = int(a) for i in range(1, a+1): if i%2 == 0 or i%3 == 0: if i%6 == 0: pass else: print(i) ``` * 使用continue完成上一題 ```python= a = input("Please input an int:") a = int(a) d=[] for i in range(1, a+1): if i%6 ==0: continue if i%2 == 0 or i%3 == 0: d.append(i) print(len(d)) ``` ## while範例程式 - 割線勘根法 ```python= err_num = 0.0001 a=-10 b=-9 while abs(a-b) > err_num: fa = a**2-6*a+4 fb = b**2-6*b+4 x1 = a-(b-a)*fa/(fb-fa) a, b = b, x1 print(b) ``` ## 自定義函數 - 修改平年閏年的程式 ```python= def g(year): if year%4 == 0: if year%100 == 0: if year%400 == 0: print('閏年') else: print('平年') else: print('閏年') else: print('平年') years = input("Please input a year:") years = int(years) g(years) ``` #### 遞迴函數 - Cn取r ```python= def C(n, r): if r == 0 or n == r: ans = 1 else: ans = C(n-1, r-1)+C(n-1, r) return ans s = C(4, 2) print(s) ``` ## 動態規劃 - 費式數列 ```python= F=[] F.append(1) F.append(1) n = input("Please input a number:") n = int(n) for i in range(2, n+1): F.append(F[i-1]+F[i-2]) print(F[n]) ``` - 最大公因數 ```python= a=96 b=36 F=[] F.append(a) F.append(b) i = 2 while True: t = F[i-2]%F[i-1] F.append(t) i = i+1 if t == 0: break print(F[-2]) ``` ## 排序法 - 相關連結 - [wiki](https://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95) - [TED-Ed](https://www.youtube.com/watch?v=WaNLJf8xzC4) - [heap sort](https://www.youtube.com/watch?v=es2T6KY45cA) - [各種排序法排序過程的影片](https://www.youtube.com/watch?v=8oJS1BMKE64&list=PLZh3kxyHrVp_AcOanN_jpuQbcMVdXbqei&index=1) - 氣泡排序法 ```python= L = [123, 456406 ,5, 6, 40, 0] n=len(L) for j in range(n): for i in range(n-1): if L[i] > L[i+1]: L[i], L[i+1] = L[i+1], L[i] ``` ## python套件 ### tkinter - 版面編排 * pack():依序堆疊 * grid(row=0, column=1, padx=10, pady=10, rowspan=2, columnspan=2) * place(x=10, y=10, anchor='nw') * ![](https://i.imgur.com/GZvssq7.png) - 相關自學網站:[莫煩python tkinter](https://morvanzhou.github.io/tutorials/python-basic/tkinter/) - 參考範例 ```python= import tkinter as tk win = tk.Tk() win.title('tk test') win.geometry('300x200') win.resizable(1, 0) t = 0 def on_click(): global t, L t=t+1 L.config(text=str(t)) b = tk.Button(win, text='hit me', width=20, height=5, bg='green', command=on_click) b.pack() L = tk.Label(win, text='hello', width=20) L.pack() e = tk.Entry(win) e.pack() win.mainloop() ``` - 猜數字 ```python= import tkinter as tk import random ans = random.randint(1, 100) #產生亂數 #視窗基本設定 win = tk.Tk() win.title('tk test') win.geometry('300x200') win.resizable(1, 0) t = 0 #判斷要大一點還是小一點 def on_click(): global t, L, ans, e, L2 guest_num = int(e.get()) if guest_num > ans: L2.config(text='Smaller') elif guest_num < ans: L2.config(text='Bigger') else: L2.config(text='Get it!!') b = tk.Button(win, text='Guest!', width=20, command=on_click) L = tk.Label(win, text='Guest a number between 1 and 100', width=30) e = tk.Entry(win) L2 = tk.Label(win, text='', width=20) L.pack() b.pack() e.pack() L2.pack() win.mainloop() #執行視窗 ``` - Scale ```python= import tkinter as tk import pylab as plt import numpy as np win = tk.Tk() win.title('tk test') win.geometry('300x600') win.resizable(1, 1) #初始化圖片 fig = plt.figure() ax = fig.subplots() a=0 b=0 x = list(np.arange(-10, 10, 0.1)) y=[] for i in range(len(x)): ans = 0 y.append(ans) p, = ax.plot(x, y) ax.set_ylim([-10, 10]) def draw_a(value): global a, b, p a = float(value) #更新全域變數數值 x = list(np.arange(-10, 10, 0.1)) y=[] #用for迴圈描點 for i in range(len(x)): ans = a*x[i]+b y.append(ans) p.set_data(x, y) #plot資料更新 fig.canvas.draw() #圖片更新 def draw_b(value): global a, b, p b = float(value) #更新全域變數數值 x = list(np.arange(-10, 10, 0.1)) y=[] #用for迴圈描點 for i in range(len(x)): ans = a*x[i]+b y.append(ans) p.set_data(x, y) #plot資料更新 fig.canvas.draw() #圖片更新 #建立scale s1 = tk.Scale(win, from_=0, to=1, resolution=0.1, orient=tk.HORIZONTAL, length=350, showvalue=1, tickinterval=0.5, label = 'a', command=draw_a) s2 = tk.Scale(win, from_=0, to=1, resolution=0.1, orient=tk.HORIZONTAL, length=350, showvalue=1, tickinterval=0.5, label = 'b', command=draw_b) s3 = tk.Scale(win, from_=0, to=1, resolution=0.1, orient=tk.HORIZONTAL) s1.pack() s2.pack() s3.pack() win.mainloop() ``` - 進階版 ```python= import tkinter as tk import pylab as plt import numpy as np win = tk.Tk() win.title('tk test') win.geometry('300x600') win.resizable(1, 1) fig = plt.figure() ax = fig.subplots() a=0 b=0 c=0 x = list(np.arange(-10, 10, 0.1)) y=[] for i in range(len(x)): ans = 0 y.append(ans) p, = ax.plot(x, y) ax.set_ylim([-10, 10]) def draw(): global a, b, c, p x = np.linspace(-10, 10, 500) #y = a*np.cos(x*b)+c #y = x**a+b y = 2**(-a*x)*np.cos(x*b)+c p.set_data(x, y) fig.canvas.draw() def draw_a(value): global a a = float(value) draw() def draw_b(value): global b b = float(value) draw() def draw_c(value): global c c = float(value) draw() s1 = tk.Scale(win, from_=0, to=5, resolution=0.1, orient=tk.HORIZONTAL, length=350, showvalue=1, tickinterval=0.5, label = 'a', command=draw_a) s2 = tk.Scale(win, from_=0, to=5, resolution=0.1, orient=tk.HORIZONTAL, length=350, showvalue=1, tickinterval=0.5, label = 'b', command=draw_b) s3 = tk.Scale(win, from_=0, to=5, resolution=0.1, orient=tk.HORIZONTAL, length=350, showvalue=1, tickinterval=0.5, label = 'c', command=draw_c) s1.pack() s2.pack() s3.pack() win.mainloop() ``` ### matplotlib [plot參考](https://matplotlib.org/users/pyplot_tutorial.html) - 基本語法 ```python= from pylab import plt fig = plt.figure() #產生圖表 ax= fig.subplots() #產生座標軸 ''' x0 = 1 y0 = 1 x1 = 2 y1 = 3 x2 = 3 y2 = 2 x= [x0, x1, x2] y=[y0, y1, y2] ''' #畫圖 p, = ax.plot([1, 2, 3], [1, 3, 2], 's--') p1, = ax.plot([1, 2, 3], [10, 30, 20], 'b') plt.show() ``` - 顏色代號 | Alias | Color | | -------- | -------- | | ‘b’ | blue | | ‘g’ | green | | ‘r’ | red | | ‘c’ | cyan | | ‘m’ | magenta | | ‘y’ | yellow | | ‘k’ | black | |‘w’ | white | ### numpy - ```np.arange(a, b, c)```:跟```range(a, b, c)```的功能完全一樣,而且arange可以放浮點數 - ```np.linspace(start, stop, number)```:產生number數量的線性array,start<=i<=stop ### vpython - [VPhysics NTU](http://tcjd71.wixsite.com/vpython) ### 開啟檔案 ```python= f = open('test.txt','r') #用r的方法開啟檔案 f = f.readlines() #讀取f檔中的內容,存到List中,以行為單位 ``` #### python字串處理 - len(<str>):取得字串長度 - list(<str>):將字串轉型成list, 每個字元為一個list成員 - <list> = <str>.split(<分割字串>):依照<分割字串>分割<str>,結果存到一個list中 - <str>[index]:讀取字串的第index個字元 ### List之list()使用方法 ```python= list( List ) ``` ### python 字串型態\反斜線使用 ``` \\ 反斜線 \' 單引號 ' \" 雙引號 " \0 空字元 \n 換行 \r 歸位 \t Tab \ooo 以8 進位數指定字元,最多三位數 \xhh 以16進 位數指定字元,至少兩位數 \uhhhh 以Unicode 16位元編碼指定字元 \Uhhhh 以Unicode 32位元編碼指定字元 ``` ### python Split()使用方法 ```python= string.split( '分隔符號' , 分隔次數 ) #分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。 #實例 str = "Line1-abcdef \nLine2-abc \nLine4-abcd"; #字串str print str.split( ); #split by default print str.split(' ', 1 ); #split by space空格 且只分隔一次 #輸出結果 #['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] 第五行 #['Line1-abcdef', '\nLine2-abc \nLine4-abcd'] 第六行 #ref:http://www.runoob.com/python/att-string-split.html ``` ### python 解析純文字檔實作 [LED IV curve data](https://drive.google.com/open?id=1kbYnpBsYoLA-o8zPJrIgfZgHfjFuOb7F) ```python= import pylab as plt #記得import pylab f = open('Y5.csv', 'r') f = f.readlines() time=[] v1=[] v2=[] for i in range(2, len(f)): g = f[i] g = g.split(',') time.append(float(g[0])) v1.append(float(g[1])) v2.append(float(g[2])) fig = plt.figure() #剛這邊有筆誤,請複製的人更正一下 ax = fig.subplots() p,=ax.plot(time,v) p2, = ax.plot(time,v2) ``` #### add_subplot例子 ```python= import pylab as plt f = open('Y5.csv', 'r') f = f.readlines() time=[] v1=[] v2=[] for i in range(2, len(f)): g = f[i] g = g.split(',') time.append(float(g[0])) v1.append(float(g[1])) v2.append(float(g[2])) fig = plt.figure() ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2) ax1.set_title('I-V curve') ax2.set_title('V-t curve') fig.suptitle('LED curve') p, = ax1.plot(v1, v2, '.') p1, = ax2.plot(time, v1) p2, = ax2.plot(time, v2) ``` ### 相對路徑/絕對路徑 閱讀資料 REF http://www.itread01.com/content/1503829342.html ## 其它參考資料 - [分數處理](http://blog.csdn.net/baiyibin0530/article/details/77197302) ## 交作業 ![](https://i.imgur.com/bVRtHRq.png) ## 專題 1. 乘乘樂:阿中是個整數狂,看到數字都情不自禁的想把每個位數都乘在一起。例如看到 356 就會想要知道 3 * 5 * 6 的值為何。快寫個程式幫幫為了乘數字而快發瘋的阿中吧! 2. 最大公因數 G.C.D & L.C.M 3. 身分證字號檢驗 * 中哥國際資訊集團接了一個專案,其中「使用者註冊」時必須輸入身分證字號,由於該集團的 CEO:中哥是一個嚴謹的人,要求必須驗證使用者所輸入的身分證字號是否正確。你!是一個菜鳥工程師負責寫這段程式碼,以你深厚的程式設計功力,相信你一定不會讓中哥失望的,對不對? * 驗證規則 * 英文轉成的數字, 個位數乘9,再加上十位數的數字 * 各數字從右到左依次乘1、2、3、4....8 * 加總以上的數字後,除以10,若可整除則為正確的身分證字號。 4. 態度的重要性 * 中哥國際資訊集團的大家長:中哥,喜歡態度良好,認真學習的學生,他認為態度很重要,因為如果我們把英文字母依序編號:A 1, B 2, C 3, … , Z 26,則 * KNOWLEDGE 只有 96 * ATTITUDE 是 100 * 你是一位年輕有為,又有思考力的好青年,你想找一個英文字給中哥打臉,雖然你知道你這樣做,成績會岌岌可危,但天生反骨的你,還是決定寫一個程式來加速尋找的過程,程式輸入一個字串(可能大小寫混雜,也可能有非英文字母的符號),然後算出該字串的得分。 * 例如:AttiTuDE 100 (英文大小寫不影響結果)、P@HP Fail (有非英文字母符號) 5. 二元一次聯立方程式機算機 * 輸入兩個聯立方程式的所有係數,印出x和y的解 * 進階:用pylab畫出兩個方程式,並標出焦點 * 參考:[克拉馬公式](https://zh.wikipedia.org/wiki/%E5%85%8B%E8%90%8A%E5%A7%86%E6%B3%95%E5%89%87) :::info a1\*x+b1\*y=c1 a2\*x+b2\*y=c2 delta = a1\*b2-a2\*b1 dx = c1\*b2-c2\*b1 dy = a1\*c2-a2\*c1 x = dx/delta y = dy/delta 如果detlta=0,則無解或無限多解 ::: 6. 猜數字遊戲1A2B * 由電腦亂數產生一個數字,接下來由玩家輸入一個數字,程式回印幾A幾B * ### 身分證字號英文對照表![](https://i.imgur.com/l9gKyd7.png) ### 驗證規則 ![](https://i.imgur.com/245fxZb.jpg)