简体   繁体   中英

creating polynomial in python by reading coefficient from a file

I'm new to 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"

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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