本文介绍了在python中生成多项式lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使以下代码通用,而不必总结不同之处情况:

How to make the following code generic, without summing up the differentcases:

def poly(n):
    if n == 1: return lambda x,a,b: x*a+b
    if n == 2: return lambda x,a,b,c: x*x*a+x*b+c
    if n == 3: return lambda x,a,b,c,d: x*x*x*a+x*x*b+x*c+d

推荐答案

您可以传递系数列表并手动"评估多项式:

you could pass a list of coefficients and evaluate the polynomial "manually":

def fn1(coefs):
    def g(x):
        ret = coefs[0]
        for i in range(1, len(coefs)):
            ret *= x
            ret += coefs[i]
        return ret

    return g

def fn2(coefs, x):
    ret = coefs[0]
    for i in range(1, len(coefs)):
        ret *= x
        ret += coefs[i]
    return ret


x = 2.5
g = fn1([2, 3, 4])
assert( g(x) == 2*x*x + 3*x + 4 )

assert( fn2([2, 3, 4], x) == 2*x*x + 3*x + 4 )

这篇关于在python中生成多项式lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 04:52