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

範例:sum

iai

對於物件的+,-,*,/,若結果是要回存物件本身會建議使用+=,-=,*=,/=:

後者是以a物件出發的method,其數值操作直接在a值的記憶體位置作用。前者會先另開一塊記憶體去算a+5,最後再去改變a的記憶體內容。

Mij=M[i][j]:

  1. 給定i=0, 計算jM0j
  2. 計算ijMij

找出每個danceInfo[i]下的showInfo有多少場訊息,並加總計算所有dance的全部場次數。

for loop的iterator會儲存最後一個iterate值,要小心後面有用到同樣的iterator變數名稱:

  • 多層迴圈建議以數學下標習慣i, j, k, …,才不會有上述錯誤。

4.2 while-loops

while <condition>:
    body

post-code
  • <condition>為True時,執行body;執行完再看<condition>, 若還是True,則繼續下去。

  • <condition>使用如if <condition>中的Boolean邏輯判斷寫法。

範例:

找出x中的第一個負值:

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)(xx0)+f(x0)

The x-intercept is the solution x1 of the equation

0=f(x0)(x1x0)+f(x0)

and we solve for x1

x1=x0f(x0)f(x0)

If we implement this procedure repeatedly, then we obtain a sequence given by the recursive formula

xn+1=xnf(xn)f(xn)

which (potentially) converges to a solution of the equation f(x)=0.

我們使用Newton’s method去找以下函數的根: p(x)=x3x21

  1. 使用def p(x):定義此函數。

  2. 使用def dp(x):定義此函數的一次微分。

  3. x0=1,計算Newton公式下的x1p(x1)值。

  4. 承上,計算Newton公式下的x2p(x2)值。

  5. 寫一個迴圈求一個x使得p(x)很接近0(接近的定義為|p(x)|<1010,取絕對值可用abs(), 1010可寫成1e-10)。