Suppose I have the following list:
f=[1, 3, 4, 5, 3, 4, 5, 6, 6, 3, 3, 1, 1, 4, 2]
I can count how many of each integers exists in the list using two methods.
First:
from collections import Counter
Counter(f)
#Counter({1: 3, 2: 1, 3: 4, 4: 3, 5: 2, 6: 2})
or second:
[[x,f.count(x)] for x in set(f)]
#[[1, 3], [2, 1], [3, 4], [4, 3], [5, 2], [6, 2]]
the second method is preferable as it throws me with a list.
Now I want to turn the output into polynomial where the first element of sublists would be power of x and the second element of sublists would be the coefficients and finally sum them to form a polynomial, such that I get:
3 x + x^2 + 4 x^3 + 3 x^4 + 2 x^5 + 2 x^6
To make this polynomial I used Sympy as follow:
from sympy import Array, tensorproduct
from sympy.abc import x
from sympy import transpose
A = Array([x])
B = Array([x[1] for x in [[x,f.count(x)] for x in set(f)]])
tensorproduct(A, B)
#[[3*x, x, 4*x, 3*x, 2*x, 2*x]]
now I am not sure how to raise for the correct power of x ? Also is there a better solution for this?
解决方案
this should work for you:
from sympy import poly, var
from collections import Counter
x = var("x")
f = [1, 3, 4, 5, 3, 4, 5, 6, 6, 3, 3, 1, 1, 4, 2]
count = Counter(f)
p = sum(coeff * x ** exp for exp, coeff in count.items())
# 2*x**6 + 2*x**5 + 3*x**4 + 4*x**3 + x**2 + 3*x