python用函数做乘法加法运算_Python实现一元多项式的相加相乘运算

自己亲手写的,没有参考,写了改改了写。个人感觉c语言版本的会更好些,因为多个指针,Python用链表自己就是多设了头结点,然后只用各个节点的指针来实现。

class ListNode:

def init(self, x, y):

self.c = x

self.e = y

self.next = None

class Solution:

def ReadandLink(self,N):

self.N=N

a0=ListNode(0,0)

a0.next=None

c0=a0

for i in range(1,N+1):

c=int(input("系数:"))

e=int(input("指数:"))

b0=ListNode(c,e)

a0.next=b0

a0=b0

return c0

def add(head1,head2):

node1=head1.next

node2=head2.next

add0=ListNode(0,0)

add0.next=None

head3=add0

while(node1!=None and node2!=None):

if(node1.e==node2.e ):

add1=ListNode(node1.c+node2.c,node1.e)

add0.next=add1

add0=add1

node1=node1.next

node2=node2.next

elif(node1.e>node2.e ):

add1=ListNode(node1.c,node1.e)

add0.next=add1

add0=add1

if(node1.next!=None):

node1=node1.next

else:

node1=node1.next

break

elif(node1.e

add1=ListNode(node2.c,node2.e)

add0.next=add1

add0=add1

if(node2.next!=None):

node2=node2.next

else:

node2=node2.next

break

while(node1==None and node2!=None):

add1=ListNode(node2.c,node2.e)

add0.next=add1

add0=add1

if(node2.next!=None):

node2=node2.next

else:

break

while(node2==None and node1!=None):

add1=ListNode(node1.c,node1.e)

add0.next=add1

add0=add1

if(node1.next!=None):

node1=node1.next

else:

break

return head3

def multi(head1,head2):

multi_node1=head1.next

multi_node2=head2.next

add_two=ListNode(0,0)

add_two.next=None

while( multi_node1!=None):

multi0=ListNode(0,0)

multi0.next=None

head4=multi0

while(multi_node2!=None):

multi_c=multi_node1.c*multi_node2.c

multi_e=multi_node1.e+multi_node2.e

multi1=ListNode(multi_c,multi_e)

multi0.next=multi1

multi0 = multi1

multi_node2=multi_node2.next

multi_node2=head2.next

multi_node1=multi_node1.next

add_two=add(add_two,head4)

return add_two

t1=Solution()

t2=Solution()

N1=int(input("多项式的项数:"))

head1=t1.ReadandLink(N1)

N2=int(input("多项式的项数:"))

head2=t2.ReadandLink(N2)

head3=add(head1,head2)

first=head3.next

print("加和结果")

while(first!=None):

print("系数=%d 指数等于%d"%(first.c,first.e))

first=first.next

head4=multi(head1,head2)

second=head4.next

print("乘积结果")

while(second!=None):

print("系数=%d 指数等于%d"%(second.c,second.e))

second=second.next

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值