2016-07-29 31 views
0

好吧,我不認爲這個問題已經在這裏回答過。瞭解Python元組和重新分配

我想知道Python是如何執行這個for循環。僅供參考,這是第2課從6.00SC MIT OCW的一部分:

def evaluate_poly(poly, x): 
    """ Computes the polynomial function for a given value x. Returns that value. 

    Example: 
    >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 
    >>> x = -13 
    >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 
    180339.9 
    poly: tuple of numbers, length > 0 
    x: number 
    returns: float """ 

    ans = 0.0 
    for i in xrange(len(poly)): 
     ans += poly[i] * (x ** i) 
    return ans 

如何for循環是由行執行行任何人能解釋一下嗎?我知道i變量被創建爲運行5次(poly多元組的長度),其中ans在每次迭代中被更新。我感到困惑的地方是每次重新分配我的時間。

通過ANS第三時間= 0.0 +(5)* X **(2)

它我認爲聚[i]的斂索引號碼(5),但那麼x乘以我的權力,這是現在的指數位置本身(2)。這正是它應該做的事情,但我無法理解我可以如何看起來既是索引號碼又是索引位置。

我是編程新手,所以任何信息都將是一個巨大的幫助。

非常感謝!

+0

ns = 0.0'把'import pdb; pdb.set_trace()'。 [這裏是一個關於這個主題的好教程](https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/) –

+0

'x ** i'的意思是「x對我的力量」,這幾乎是你期望在多項式中看到的。 – khelwood

+0

'x ** i'不是'x'乘以'i'。這是'我'的力量的'x'。 –

回答

1

i被分配給循環中的這些數字:0,1,2,3,4,因爲xrange創建了一個從0到參數減1的範圍。參數是len(poly),返回5(大小。陣列因此i從0分配至4(= 5-1)

第一迭代i等於0:

聚[0]實際上等於聚的第一元件(0.0)

的公式然後變成:

ans += poly[i] * (x ** i) 
ans = ans + poly[i] * (x ** i) 
ans = 0.0 + poly[0] * (-13 in the power of 0) 
ans = 0.0 + 0.0 * (-13 in the power of 0) 
ans = 0.0 

下一迭代i等於1:

ans = ans + poly[i] * (x ** i) 
ans = 0.0 + poly[1] * (-13 in the power of 1) 
ans = 0.0 + 0.0 * (-13 in the power of 1) 
ans = 0.0 

下一個迭代i等於2:

ans = ans + poly[i] * (x ** i) 
ans = 0.0 + poly[2] * (-13 in the power of 2) 
ans = 0.0 +  5.0 * (-13 in the power of 2) 

下一個迭代i等於3:

ans = ans + poly[i] * (x ** i) 
ans = 5.0 * (-13 in the power of 2) + poly[3] * (-13 in the power of 3) 
ans = 5.0 * (-13 in the power of 2) +  9.3 * (-13 in the power of 3) 

最後迭代i等於4:

'a'之前的線上的
ans = ans + poly[i] * (x ** i) 
ans = 5.0 * (-13 in the power of 2) + 9.3 * (-13 in the power of 3) + poly[4] * (-13 in the power of 4) 
ans = 5.0 * (-13 in the power of 2) + 9.3 * (-13 in the power of 3) +  7.0 * (-13 in the power of 4) 
+0

這正是我所尋找的。感謝您的詳細澄清。 – Chris