python多项式运算字典_使用字典在Python中乘法多项式

本文介绍了一个使用字典表示多项式的Python类,通过字典键表示指数,值表示系数。实现了多项式的比较、加法和乘法运算。在乘法运算中,虽然指数计算正确,但中间项的系数出现错误。作者寻求如何在乘法过程中优雅地利用加法运算以修正这一问题。
摘要由CSDN通过智能技术生成

我写了一个小类,它的初始值设定项将字典作为参数。下面的字典{2:3, 4:5, 6:7}翻译成多项式3x^2 + 5x^4 + 7x^6,所以我的字典的键是指数,它的值是系数。在

我已经成功地使用eq方法实现了类中两个多项式的比较,我可以添加它们。这是我的代码:class Polynomial(object):

def __init__(self, polynom = {}):

self.polynom = polynom

self.poly_string = self.nicePolynom(polynom) #just a method that will make my output look nice

def __str__(self):

return self.poly_string # for debugging purposes

def coefficient(self, exponent):

"""

A small function that returns the coefficient of the corresponding exponent

i.e. if our Polynomial is P = 3x^9 then p.coefficient(9) return 3

"""

try:

return self.polynom[exponent]

except KeyError:

pass

def __add__(self,other):

"""

Overloading the + operator

Not the most elegant solution but easily understandable.

We check first if our exponent is present in both polynomials

then if its only present in one and the symmetric case, adding the result

to the dictionary add

"""

add = {}

for exponent in self.polynom:

if exponent in other.polynom:

add[exponent] = self.polynom[exponent] + other.polynom[exponent]

for exponent in self.polynom:

if exponent not in other.polynom:

add[exponent] = self.polynom[exponent]

for exponent in other.polynom:

if exponent not in self.polynom:

add[exponent] = other.polynom[exponent]

return add

def __mul__(self, other):

mult = {}

for exponent1 in self.polynom:

for exponent2 in other.polynom:

mult[exponent1 + exponent2] = self.coefficient(exponent1) * other.coefficient(exponent2)

return mult

关键的一步,也是我的主要问题是,在乘法的过程中,我想利用加法。但是我对OOP绝对是新手,我不知道如何初始化一个Polynom对象来执行加法运算。在

如果我把一个多项式乘以它本身,我得到了正确的指数,但是除了初始项和结束项,所有的系数都离得很远。在

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值