python写程序求多项式的和_拥有列表并尝试在Python中创建多项式(符号计算)

1586010002-jmsa.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值