--- title: python讀書會(五) tags: python讀書會 notes: 0.00011001100110011.....、(https://www.programiz.com/python-programming/methods/built-in) --- {%hackmd @themes/orangeheart %} ## 5.0 回顧... 1. 變數的有效域(```global```、```nonlocal```) 2. 其他的keywords(```del```、```pass```、```lambda```) 3. 命名規則、數值簡述、陣列簡述(tuple、list、set、dictionary) ## 5.1 模組 :::success 嘗試看看將十進位的0.1分別轉換成二進位的小數和分數形式。 ::: 模組(Module)就是一個檔案,包含了相關性較高的程式碼。隨著應用程式的開發規模越來越大,我們不可能把所有的程式碼都寫在同一份Python檔案中,一定會將關聯性較高的程式碼抽出來放在不同的檔案中來形成模組。 - [ ] 程式碼 5.1 ```python= # 想知道這個模組裡面有什麼東西可以用 print(dir(模組)) # 如果作者有好好寫文檔(.doc)的話,這個可以知道詳細功能 print(help(模組)) # 模組的路徑 import 模組 print(模組.__file__) ``` #### 5.1.1 math 模組 上次我們知道```math```這個模組讓我們可以在python上運行不簡單的運算。 像是:$\pi$、$\cos$、$e$、$\log$、$\sinh$、$n!$、$\sqrt[2]{n}$ ... 在此之前,要先了解到以下兩者的差別: ```python import math as m print(m.e) from math import * print(e) ``` - [ ] 程式碼 5.1.1a ```python= math.ceil(x)#回傳一個大於等於x的最小整數 math.copysign(x, y)#讓x變成y的同號數 #基本上看見f開頭的通常是回傳float型態 math.fabs(x)#絕對值 math.factorial(x)#階乘 math.floor(x)#取高斯,和ceil相反 math.fmod(x, y)#取x/y的餘數 math.frexp(x)#取尾數和指數(科學記號) math.fsum(iterable)#將所有的iterable值加總,像是list型態 math.isfinite(x)#x是有限值,則回傳True math.isinf(x)#x是無限值,則回傳True math.isnan(x)#x是NaN,回傳True math.ldexp(x, i)#相當於x*(2**i) math.modf(x)#回傳x的小數和整數部分 math.trunc(x)#只取x的整數部分 math.exp(x)#e**x math.expm1(x)#e**x-1 math.log(x, b)#以b為底,取x的對數 math.log1p(x)#ln(1+x) math.log2(x)#以2為底,取x的對數 math.log10(x)#以10為底,取x的對數 math.pow(x, y)#x**y math.sqrt(x)#x**0.5 math.acos(x)#arccos(x),弳度制 math.asin(x)#arcsin(x),弳度制 math.atan(x)#arctan(x),弳度制 math.atan2(y, x)#arccos(y/x),弳度制 math.cos(x)#cos(x),弳度制 math.hypot(x, y)#返回兩股斜邊長sqrt(x*x + y*y)(Euclidean norm) math.sin(x)#sin(x),弳度制 math.tan(x)#tan(x),弳度制 math.degrees(x)#將弳度轉換成角度制 math.radians(x)#將角度轉換成弳度制 math.acosh(x)#雙曲餘弦反函數,arccosh(x) math.asinh(x)#雙曲正弦反函數,arcsinh(x) math.atanh(x)#雙曲正切反函數,arctanh(x) math.cosh(x)#雙曲餘弦函數,cosh(x) math.sinh(x)#雙曲正弦函數,sinh(x) math.tanh(x)#雙曲正切函數,tanh(x) math.erf(x)#回傳x的誤差函數值(自己去wiki查) math.erfc(x)#回傳x處的互補誤差函數值 math.gamma(x)#回傳x處的gamma函數 math.lgamma(x)#log(abs(gamma(x))) math.pi math.e ``` #### 5.1.2 random 模組 上次也稍微提到了```random```,專們用來產生隨機變數的模組。 當你想產生隨機變數但是又怕一不小心內核重置,原本的數據就搞丟時,可以使用```seed()```來固定住隨機值。 - [ ] 程式碼 5.1.2a ```python= #這是上次的程式碼4.3.2f加上seed() import random random.seed(2)#改變seed內數字就可以改變隨機值 print(random.randrange(10, 20))#兩個整數之間取一個隨機整數 x = ['a', 'b', 'c', 'd', 'e'] print(random.choice(x))#在list或tuple中隨機挑一個 random.shuffle(x)#將原本的list打亂 print(x) print(random.random())#0~1之間隨機取一個float ``` - [ ] 程式碼 5.1.2b ```python= getstate() setstate(state) getrandbits(k)#0~2**k選擇數字 randrange(start, stop, step)#隨機整數 randint(a, b)#隨機整數 choice(list)#list中的一個隨機元素 shuffle(list)#顧名思義:洗牌 sample(list, k)#取樣k個 random()#0~1隨機float uniform(a, b)#a~b隨機float triangular(low, high, mode)#? betavariate(alpha, beta)#beta distribution expovariate(lambd)#exponential distribution gammavariate(alpha, beta)#gamma distribution gauss(mu, sigma)#gaussian distribution lognormvariate(mu, sigma)#log normal distribution normalvariate(mu, sigma)#normal distribution vonmisesvariate(mu, kappa)#vonmises distribution paretovariate(alpha)#pareto distribution weibullvariate(alpha, beta)#weibull distribution ``` 看見產生這麼多隨機變數,裡面有很多不同種類的分佈,我們來稍微看一下下~~ :::info :snail: **Beta distribution** ![](https://i.imgur.com/HWFtq7D.png =400x) 圖片來源:wikipedia ::: :::success :snail: **Exponential distribution** ![](https://i.imgur.com/7kwMicM.png =400x) 圖片來源:wikipedia ::: :::warning :snail: **Gamma distribution** ![](https://i.imgur.com/ETc2jB5.png =400x) 圖片來源:wikipedia ::: :::danger :snail: **Gaussian distribution(Normal distribution)** ![](https://i.imgur.com/7mi9E7a.png =400x) 圖片來源:wikipedia ::: :::info :snail: **Log normal distribution** ![](https://i.imgur.com/y67gmnb.png =400x) 圖片來源:wikipedia ::: :::success :snail: **Von mises distribution** ![](https://i.imgur.com/6bNmuH3.png =400x) 圖片來源:wikipedia ::: :::warning :snail: **Pareto distribution** ![](https://i.imgur.com/9wuaA8I.png =400x) 圖片來源:wikipedia ::: :::danger :snail: **Weibull distribution** ![](https://i.imgur.com/ZNOND8X.png =400x350) 圖片來源:wikipedia ::: #### 5.1.3 python 內建函數 不用import任何模組(module)或是套件(packages),我們直接就能在python中使用。 - [ ] 程式碼 5.1.3a ```python #因為我好懶惰,這邊各個函數的功能交給大家去找,並且標註上去~(共76行) abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reverse() zip() compile() hasattr() memoryview() round() sorted() complex() hash() min() set() delattr() help() next() setattr() dict() hex() object() slice() dir() id() oct() #在這邊欠揍的說一句:"加油~~" ``` ![](https://i.imgur.com/fuT5Tpm.jpg =600x) ## 5.2 數據類型 在這個部分介紹4種類型:```tuple```、```list```、```set```、```dictionary``` 先來比較一下它們的差異... ![](https://i.imgur.com/pElocLD.png =450x) - [ ] 程式碼 5.2 ```python= L1 = ["hello", 1, 4, 8, "good"] print(L1) L1[0] = "morning" print(L1) print(L1[4]) print(L1[-1]) print(L1[1:4]) L2 = ["apple", "mango", "banana", 1, 4] print(L1 + L2) ``` 嘗試看看如果把程式碼5.2的list型態資料原封不動地改成tuple、set,會發生什麼事? #### 5.2.1 tuple 當只有一個元素時,```tuple = ('hi',)```,否則它的型態不是tuple 佔用空間、運作速度都比list強。 #### 5.2.2 list 不同於tuple型態資料,list的自由度非常高,因此許多簡單暫存的資料都常常用list來表示。 - [ ] 程式碼 5.2.2a ```python= my_list = ['p', 'r', 'o', 'b', 'e'] print(my_list[0])#提取序號只能是整數 print(my_list[2]) print(my_list[5]) #error print(my_list[-1]) print(my_list[-5]) ``` ![](https://i.imgur.com/9hUZ8Rx.png =400x) - [ ] 程式碼 5.2.2b ```python= my_list = ['p','r','o','g','r','a','m','i','z'] print(my_list[0:8]) print(my_list[:9]) print(my_list[:]) ``` - [ ] 程式碼 5.2.2c ```python= n_list = ["Happy", [2, 0, 1, 5]] print(n_list[0][1]) print(n_list[1][3]) ``` - [ ] 程式碼 5.2.2c ```python= #list基本功能 list.append(element) list.insert(index, element) list.extend(seq) list.pop(index) list.remove(element) list.clear() list.count(element) list.index(element) list.reverse() cmp(list1, list2) len(list) max(list) min(list) list(seq)#將別的數據型態轉換成list,嘗試看看將set轉換成list~~ #基本操作 #['Hi!'] * 4 #3 in [1, 2, 3] #for x in [1, 2, 3]: ``` ## Homework 5 [d010: 盈數、虧數和完全數(zerojudge)](https://zerojudge.tw/ShowProblem?problemid=d010) [d562: 山寨版磁力蜈蚣(zerojudge)](https://zerojudge.tw/ShowProblem?problemid=d562) [a042: 平面圓形切割](https://zerojudge.tw/ShowProblem?problemid=a042) * 刷題除了使用zerojudge以外,也可以嘗試英文版的[online judge](https://onlinejudge.org)