拥有列表并尝试在Python中创建多项式(符号计算) [英] Having a list and trying to make a polynomial in Python (symbolic calculation)
问题描述
假设我有以下列表:
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.
第一:
from collections import Counter
Counter(f)
#Counter({1: 3, 2: 1, 3: 4, 4: 3, 5: 2, 6: 2})
或秒:
[[x,f.count(x)] for x in set(f)]
#[[1, 3], [2, 1], [3, 4], [4, 3], [5, 2], [6, 2]]
第二种方法更可取,因为它会向我抛出一个列表. 现在,我想将输出转换为多项式,其中子列表的第一个元素将是x的幂,而子列表的第二个元素将是系数,最后将它们求和以形成多项式,这样我得到:
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
要使用多项式,我使用了Sympy,如下所示:
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]]
现在我不确定如何提高x的正确乘方数?还有为此更好的解决方案吗?
now I am not sure how to raise for the correct power of x ? Also is there a better solution for this?
推荐答案
这应该对您有用:
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
其中 **
用于求幂.
where **
is used for exponentiation.
这篇关于拥有列表并尝试在Python中创建多项式(符号计算)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!