2

私はこの演習を解決しようとしています:

これらの係数を持つ多項式を表す関数を返します。

たとえば、 の場合、を計算する coefs=(10, 20, 30)の関数を返します。また、関数の属性に coefs を格納し、属性に式の str を格納します。x30 * x**2 + 20 * x + 10.coefs.__name__

これが私の解決策です:

def poly(coefs):
    #write the string name
    l=len(coefs)
    coefs=reversed(coefs)
    j=0
    name=""
    for i in coefs:
        if j<l-2:
            name=name+str(i)+" * x**"+str(l-j-1)+" + "
        elif j==l-2:
            name=name+str(i)+" * x + "
        else:
            name=name+str(i)
        j=j+1
    def calc(x):
        name.replace("x",str(x))
        calc.__name__=name
        return eval(name)



    return calc

うまくいきません。

>>> p=poly((1,2,3))
>>> p
<function calc at 0x3b99938> #the name of p is not what I want!!! (*)
>>> y=p(3)
>>> p
<function 3 * x**2 + 2 * x + 1 at 0x3b99938> # now this is right!
>>> 

最初の呼び出しでも正しい名前を取得するにはどうすればよいですか (*) ?

4

1 に答える 1