通过从文件中读取系数在 python 中创建多项式
creating polynomial in python by reading coefficient from a file
我是 python 的新手。我通过从文本文件中读取多项式系数来创建多项式。当我 运行 下面的代码时,出现
错误
"TypeError: cannot accumulate on a scalar"
read_file = open('coefficient.txt','r')
coefficient = read_file.read()
p1 = poly1d([coefficient])
print(p1)
请提供您的意见
在将 string
列表传递给 poly1d 之前,您必须将其转换为 int
列表:
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)
输出:
4 3
1 x + 1 x + 1 x
我是 python 的新手。我通过从文本文件中读取多项式系数来创建多项式。当我 运行 下面的代码时,出现
错误"TypeError: cannot accumulate on a scalar"
read_file = open('coefficient.txt','r')
coefficient = read_file.read()
p1 = poly1d([coefficient])
print(p1)
请提供您的意见
在将 string
列表传递给 poly1d 之前,您必须将其转换为 int
列表:
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)
输出:
4 3
1 x + 1 x + 1 x