Python 中多项式作为输入

Chr*_*ger 4 python input polynomials

如何让 Python 将多项式作为输入,同时保持将 x 替换为实际值的能力?

这是我尝试过的:

fx=input("Enter a Polynomial: ")
x=float(input("At wich position should the polynomial be evaluated: "))

while True:
    print(eval("fx"))

    continue
Run Code Online (Sandbox Code Playgroud)

出现的问题是,Python 只会将 fx 计算为 x,而不是我通过第二个输入赋予 x 的值。

Mic*_*hał 5

这应该有帮助:

def eval_polynomial(poly, val):
    xs = [ x.strip().replace('^','**') for x in poly.split('+') ]
    return sum( [eval(n.replace('x', str(val))) for n in xs] )
Run Code Online (Sandbox Code Playgroud)

请记住,出于安全原因,您之前必须确保 val 是一个数字。

编辑:迪彭·巴克拉尼亚(Dipen Bakraniya)要求的更自我描述的版本

def eval_polynomial(poly, val):
    xs = [ x.strip().replace('^','**') for x in poly.split('+') ]
    return sum( [eval(n.replace('x', str(val))) for n in xs] )
Run Code Online (Sandbox Code Playgroud)