Python编写多项式一行代码

时间:2018-08-01 15:43:03

标签: python printing equation

我有一个多项式方程常数的列表,我想在print()函数内部用for循环编写该方程。最短的方法是什么(如果存在单行代码会更合适)?

编辑:(原因:添加样本) 代码如下:

cnst=list()
degree=int(input("Enter degree of your polynomial: "))
#degree=int(input("Enter degree of your polynomial: "))
# must use degree+1 to include constant term
for i in range(degree+1):
    print(i)
    print("Enter constant for x^" + str(degree-i) + ": ", end='')
    cnst.append(float(input()))
print (cnst)
print("\nFunction created: ")
#print equation code here <<--

2 个答案:

答案 0 :(得分:1)

欢迎来到NumPy的Pythonic数学领主和救世主。

您可以添加,减去,计算导数等。np.polynomial模块具有很多功能。现在,在处理多项式时,numpy.polynomial是推荐的类。查看文档以了解更多信息。

from numpy.polynomial import Polynomial

p1 = Polynomial([1,5,2])

p2 = Polynomial([6,1,4,3])

print(p1 * p2)
  

多项式([6.,31.,21.,25.,23.,6.],[-1。,1.],[-1。,1。])

答案 1 :(得分:0)

我无法正确理解,但我认为这段代码可以为您提供帮助

for x in [-1, 0, 2, 3.4]:
print(x, p(x))