2015-09-26 40 views
0

此代碼的目的是「編寫一個函數/子gen_2nd_deg_polys,它接受一個3元組列表並返回一個匿名第二個 度多項式的列表。」 這是告訴我,「功能」對象沒有Getitem屬性。從3元組生成二次多項式

我錯過了什麼重要的關於訪問lambda內的元組?

import sys 

def gen_2nd_deg_polys(coeffs): 
    return lambda x: (
    str(coeffs[0][0]) + 'x^2 + ' + str(coeffs[0][1]) + 'x + ' + str(coeffs[0][2]) + ' at x = ' + str(x), coeffs[0][0] * x ** 2 + coeffs[0][1] * x + coeffs[0][2]) 

polys = gen_2nd_deg_polys([(1, 2, 3), (4, 5, 6)]) 

polys[0](1) 
polys[1](2) 

編輯...還是非常錯誤

def gen_2nd_deg_polys(coeffs): 
    plist = [] 
    for coeff in coeffs: 
     plist.append(lambda x, coeff=coeff:str(coeff[0]) + 'x^2 + ' + str(coeff[1]) + 'x + ' + str(coeff[2]) + ' at x = ' + str(x), coeff[0] * x**2 + coeff[1] *x + coeff[2]) 
    return plist 

polys = gen_2nd_deg_polys([(1, 2, 3), (4, 5, 6)]) 
print(polys[0](1)) 
print(polys[1](2)) 
+0

您正在返回的,而不是lambda函數列表 – inspectorG4dget

+0

我怎麼會去選出一位lambda函數lambda函數列表? –

+0

提示:'coeffs [0] [0]'從第一個3元組係數中獲得x^2的係數。來自第二個三元組的相同係數是'coeffs [1] [0]';因此第i個三元組中的x^2的係數是「coeffs [i] [0]」。現在,嘗試將該邏輯放入for循環,然後將您的lambda函數附加到列表中 – inspectorG4dget

回答

1

你有一些問題在這裏解決。首先,您的gen_2nd_deg_polys函數需要遍歷元組列表並生成一個表示來自其中每個元素的多項式的lambda對象。他們可以返回列表中,您可以索引(使用[])並調用(使用())。

一個微妙的一點就是,Python在lambda定義(見e.g. here更多關於此)結合變量引用「晚」,所以一個簡單的循環,如:

for pcoeffs in coeffs: 
    plist.append(lambda x: pcoeffs[0] * x**2 + pcoeffs[1] * x + pcoeffs[2]) 

將導致所有的lambdas使用最後coeffs遇到pcoeffs的元組(所有的多項式都是相同的)。解決此問題的方法(通常一個,據我所知)是設置pcoeffs作爲默認參數,如下:

def gen_2nd_deg_polys(coeffs): 
    plist = [] 
    for pcoeffs in coeffs: 
     plist.append(lambda x, pcoeffs=pcoeffs: pcoeffs[0] * x**2 + pcoeffs[1] * x + pcoeffs[2]) 
    return plist 

coeffs = [(1,2,3), (0,4,3), (1,5,-3)] 

polys = gen_2nd_deg_polys(coeffs) 

print polys[0](3), 1*9 + 2*3 + 3 
print polys[1](3), 4*3+3 
print polys[2](3), 1*9 + 5*3 - 3 
+0

這是有道理的,謝謝,但請檢查我的編輯代碼,這是給我的問題說全球名稱'x'沒有定義。 –

+0

有一點讓你的語法變得糟糕:嘗試'plist.append(lambda x,coeff = coeff:str(co在x ='+ str(x)+'處的+'x^2 +'+ str(coeff [1])+'x +'+ str(coeff [2])+'是'+ str (coeff [0] * x ** 2 + coeff [1] * x + coeff [2]))'所以你從'lambda'返回一個字符串。 – xnx

+0

你是專業人士。我現在看到我的語法錯了。謝謝。 –