简体   繁体   English

通过从文件中读取系数在python中创建多项式

[英]creating polynomial in python by reading coefficient from a file

I'm new to python. 我是python的新手。 I'm creating polynomial by reading polynomial coefficients from text file. 我正在通过从文本文件中读取多项式系数来创建多项式。 When I run below code, I'm getting error as 当我运行下面的代码时,出现错误

"TypeError: cannot accumulate on a scalar" “ TypeError:无法在标量上累积”

read_file = open('coefficient.txt','r')
coefficient = read_file.read()
p1 = poly1d([coefficient])
print(p1)

Please give your inputs 请输入您的意见

You have to convert string list to int list before you pass it to poly1d: 您必须先将string列表转换为int列表,然后再将其传递给poly1d:

from numpy import poly1d
read_file = open('coefficient.txt','r') # 1,1,0,1,0 store in file coefficient.txt
coefficient = read_file.readline().split(',') # coefficient =['1', '1', '0', '1', '0']
p1 = poly1d(map(int, coefficient)) #convert it to [1, 1, 0, 1, 0] with map for python2
#p1 = poly1d(list(map(int, coefficient))) #for python3
print(p1)

Output: 输出:

   4     3
1 x + 1 x + 1 x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM