2016-11-21 6 views
-4

で機能を評価:は、私は次のことを行う必要があるのPython

A function eval_f(f, xs) which takes a function f = f(x) and a list xs of values that should be used as arguments for f. The function eval_f should apply the function f subsequently to every value x in xs, and return a list fs of function values. I.e. for an input argument xs=[x0, x1, x2,..., xn] the function eval_f(f, xs) should return [f(x0), f(x1), f(x2), ..., f(xn)].

import math 


def eval_f(f, xs): 

    x = [] 
    f = f(x) 
    for i in range(len(xs)): 
     f.append(f(x[i])) 
    return f 

eval_f(math.sqrt、[1、2、4、9]) トレースバック(最新の呼び出しの最後):

C " eval_f(math.sqrt、[1、2、4、9])

ファイルで、1行目、" ファイル ":/Users/Idoia/untitled2.py"、6行目でeval_f f = f(x)

TypeError例外:フロートが必要とされて

+3

?何が起こるのですか? –

+2

あなたの質問は何ですか? –

+0

これは浮動小数点が必要であるというエラーを表示します –

答えて

0
def test(x): 
    return x*2 

def eval_f(f, xs): 
    ans = [] 
    for x in xs: 
     ans.append(f(x)) 
    return ans 

print(eval_f(test,[1,2,3,4,5])) 

プリントアウト:

[2, 4, 6, 8, 10] 
+0

ありがとうございました! –

+0

これはおそらく詳しい解答が必要な宿題だと理解していますが、Pythonでは 'map(f、list)'を使ってループを置き換えることができます。 – pie3636

+0

それは本当です。より多くの "Pythonic" – abacles

1

for an input argument xs=[x0, x1, x2,..., xn] the function eval_f(f, xs) should return [f(x0), f(x1), f(x2), ..., f(xn)].

あなたがリスト

mapに機能fをしたいのpython3を使用している場合、

def eval_f(f, xs): 
    return list(map(f, xs)) 

python2のlist()を削除できます

関連する問題