2016-11-21 2 views
-4

ich folgendes tun:auswerten Funktionen in 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]) Traceback (jüngste Aufforderung zuletzt):

Datei "", Zeile 1, in eval_f (Math.sqrt, [1, 2, 4, 9])

Datei "C: /Users/Idoia/untitled2.py", Zeile 6, eval_f f = f (x)

Typeerror: ein Schwimmer erforderlich ist

+3

entfernen? Was geschieht? –

+2

Was ist Ihre Frage? –

+0

Es zeigt einen Fehler an, der besagt, dass es einen Gleitkomma benötigt –

Antwort

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])) 

Druckt:

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

Danke das ist perfekt! –

+0

Ich verstehe, dass dies wahrscheinlich eine Art Hausaufgabe ist, wo sie eine detaillierte Lösung wollen, aber in Python könnte man einfach 'map (f, list)' machen, um die Schleife zu ersetzen. – pie3636

+0

Das stimmt. Mehr "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)].

Sie wollen map eine Funktion f über eine Liste

Wenn Python3 verwenden,

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

Sie können die list() für python2