Chapter 4 Python迴圈
4.1 for-loops
for <iterator> in <iterable>:
body
post-code
iterable objects包含:
可產生迭代值(iterate)的物件,如list, tuple, string。
iterable也可透過函數產生,如:
range()
,enumerate()
. 這些函數並不會產生list存在記憶體,而是每次要換新iterate值時才on demand的產生(省記憶體)。
4.1.1 不同iterables
dict_example = {
'list': [1, 3, -7, 4, 9, -5, 4],
'dict': {
"日期": [2001,2002,2003],
"金額": [21000,33000,45880]
},
'matrix': [
[2,5,4],
[2,-1,3]]
}
print("list")
x=dict_example["list"]
x
[i for i in x]
[i for i in range(len(x))]
[i for i in enumerate(x)] # 產生tuple iterates
print("dict")
x=dict_example["dict"]
x
[i for i in x] # key sequence
[i for i in range(len(x))] # index sequence
[i for i in enumerate(x)] # (index, key) tuple sequence
[i for i in x.items()] # (key, value) tuple sequence
範例:sum
∑iai
對於物件的+,-,*,/,若結果是要回存物件本身會建議使用+=,-=,*=,/=
:
後者是以a物件出發的method,其數值操作直接在a值的記憶體位置作用。前者會先另開一塊記憶體去算a+5
,最後再去改變a的記憶體內容。
import requests
response=requests.get("https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=3")
danceInfo=response.json()
找出每個danceInfo[i]下的showInfo有多少場訊息,並加總計算所有dance的全部場次數。
for loop的iterator會儲存最後一個iterate值,要小心後面有用到同樣的iterator變數名稱:
listA=[[1,3,5],[2,4,6]]
sum=0
for i in range(len(listA)):
for j in range(len(listA[i])):
sum +=listA[i][j]
print(sum)
listA=[[1,3,5],[2,4,6]]
sum=0
for i in range(len(listA)):
for i in range(len(listA[i])):
sum +=listA[i][i]
print(sum)
- 多層迴圈建議以數學下標習慣i, j, k, …,才不會有上述錯誤。
4.2 while-loops
while <condition>:
body
post-code
當
<condition>
為True時,執行body;執行完再看<condition>
, 若還是True,則繼續下去。<condition>
使用如if <condition>
中的Boolean邏輯判斷寫法。
範例:
fact()函數可以由fact(n)
去算n!。
n!=n(n−1)(n−2)...1
4.3 loop intervention
break
跳出迴圈continue
回到迴圈開頭
# demonstrating a `continue` statement in a loop
x = 1
while x < 4:
print("x = ", x, ">> 進入loop <<")
if x == 2:
print("x = ", x, "跳回開頭")
x += 1
continue
x += 1
print("到loop最底")
import requests
url = 'https://raw.githubusercontent.com/tpemartin/course-108-1-inclass-datavisualization/master/作品展示/homework2/homework2_008.RMD'
myFile=requests.get(url)
contentList=myFile.content.decode("utf-8").split("\n")
取出contentList中介於```{r graph}
與```
間的程式碼。
完成的內容可以用以下方式存在一個“homework2_008.R”檔案
4.4 練習:Newton’s method
Let f(x) be a differentiable function. If x0 is near a solution of f(x)=0 then we can approximate f(x) by the tangent line at x0 and compute the x-intercept of the tangent line. The equation of the tangent line at x0 is
y=f′(x0)(x−x0)+f(x0)
The x-intercept is the solution x1 of the equation
0=f′(x0)(x1−x0)+f(x0)
and we solve for x1
x1=x0−f(x0)f′(x0)
If we implement this procedure repeatedly, then we obtain a sequence given by the recursive formula
xn+1=xn−f(xn)f′(xn)
which (potentially) converges to a solution of the equation f(x)=0.
我們使用Newton’s method去找以下函數的根: p(x)=x3−x2−1
使用
def p(x):
定義此函數。使用
def dp(x):
定義此函數的一次微分。令x0=1,計算Newton公式下的x1及p(x1)值。
承上,計算Newton公式下的x2及p(x2)值。
寫一個迴圈求一個x∗使得p(x∗)很接近0(接近的定義為|p(x∗)|<10−10,取絕對值可用
abs()
, 10−10可寫成1e-10
)。