Search code examples
pythonpolynomials

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


Solution

  • 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