如何定义并实现接收次数与参数列表的降幂函数求值工具
解决方案
可以通过定义多项式类,让func函数返回该类实例,同时实现类的字符串表示与可调用特性,满足需求:
完整代码
class Polynomial: def __init__(self, degree: int, params: list): if len(params) != degree + 1: raise ValueError(f"参数列表长度应为{degree+1},对应从x^{degree}到常数项的系数") self.degree = degree self.params = params def __repr__(self): terms = [] # 从最高次项到常数项遍历系数 for idx, coeff in enumerate(self.params): current_degree = self.degree - idx if coeff == 0: continue # 处理项的符号 if terms: sign = "+" if coeff > 0 else "-" else: sign = "" if coeff > 0 else "-" abs_coeff = abs(coeff) # 处理不同次数项的格式 if current_degree == 0: term = f"{sign}{abs_coeff}" elif current_degree == 1: coeff_str = "" if abs_coeff == 1 else abs_coeff term = f"{sign}{coeff_str}x" else: coeff_str = "" if abs_coeff == 1 else abs_coeff term = f"{sign}{coeff_str}x**{current_degree}" terms.append(term) return " ".join(terms) if terms else "0" def __call__(self, x: int | float) -> int | float: result = 0 for idx, coeff in enumerate(self.params): current_degree = self.degree - idx result += coeff * (x ** current_degree) return result def func(degree: int, params: list) -> Polynomial: return Polynomial(degree, params)
测试示例
# 初始化三次多项式 f = func(3, [3, 2, -1, 8]) print(f) # 输出: 3x**3 + 2x**2 - 1x + 8 print(f(3)) # 输出: 104
代码说明
Polynomial类的__init__方法:校验参数列表长度与多项式次数是否匹配,确保输入的系数数量正确(次数为n时,需要n+1个系数,从最高次到常数项)。__repr__方法:生成多项式的降幂字符串表达式,处理了系数为1/-1、常数项、一次项的特殊格式,以及符号的正确显示。__call__方法:让类实例可以像函数一样被调用,传入数值后计算多项式在该点的取值。func函数:作为入口,接收指定的两个参数,返回Polynomial实例,符合要求的函数签名。
这种方式替代了手动编写固定次数的高阶函数,不管多项式次数是多少,只需传入次数和对应系数列表即可,扩展性更强,无需重复编写计算逻辑。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

