2014-01-06 30 views
0

我正在編寫一個程序來評估一個多項式,作爲係數元組(從0度到n度)給出。我定義函數,然後用多項式的raw_inputs和x的值來調用它。Python元組索引遞歸:「不能通過類型爲float的非int類乘法序列」

這是在Python 2.5.4

這是在編程在線課程的練習,對我的生活我想不出什麼錯誤;我的程序是相同的給出解決方案,以及,它返回相同的錯誤:

"line 19, in evaluate_poly 
    polySum += poly[n] * (x ** n) 
TypeError: can't multiply sequence by non-int of type 'float'" 

的代碼如下:

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 
    """ 

    polySum = 0.0 
    for n in xrange(0, len(poly)-1,1): 
     polySum += poly[n] * (x ** n) 
    return polySum 


function = tuple(raw_input('Enter your polynomial as a tuple of numbers, going from degree 0 to n: ')) 
x = float(raw_input('Enter the value of x for which your polynomial is to be evaluated: ')) 


print 'f(x) =', evaluate_poly(function, x) 

第一個輸入,我會做這樣的事情(1, 1,1,1)然後我會輸入1作爲第二個,並且我得到上述錯誤。

這是怎麼回事?我認爲for循環中變量n的括號只是索引元組中的每個連續值,但錯誤似乎是說poly [n]是一個序列而不是一個數字。

感謝您的幫助。

+0

試''print'ing分配function'之後 - 那會給你錯誤的根源 – MattDMo

回答

0

tuple()不會做你認爲它做的事情。改爲嘗試ast.literal_eval()

2
function = tuple(raw_input('Enter your polynomial as a tuple of numbers, going from degree 0 to n: ')) 

這條線不會做你認爲它的作用。這裏是做什麼的一個例子:

>>> function = tuple(raw_input('Enter your polynomial as a tuple of numbers, goi 
ng from degree 0 to n: ')) 
Enter your polynomial as a tuple of numbers, going from degree 0 to n: (1, 1) 
>>> function 
('(', '1', ',', ' ', '1', ')') 

它需要用戶輸入的字符串,並把它變成單個字符的元組。如果你希望用戶輸入文字的元組,並把它當作這樣,嘗試ast.literal_eval

import ast 
function = ast.literal_eval(raw_input('Enter your polynomial as a tuple of numbers, going from degree 0 to n: ')) 

雖然我們修復bug,這是值得注意的是,您的評估代碼竊聽:

for n in xrange(0, len(poly)-1,1): 

由於xrange返回的序列不包括stop參數,所以在多項式的最後一項之前停止。你想

for n in xrange(len(poly)): 

或更好,但使用enumerate,或使用不需要指數冪的評估算法:

value = 0 
for i in reversed(poly): 
    value = x*value + i 
相關問題