首页IT科技python中链表详解(python链表的乘法问题)

python中链表详解(python链表的乘法问题)

时间2025-06-21 01:55:28分类IT科技浏览4168
导读:说明...

说明

1             、左乘法约定为数乘             ,即乘以整数n                   ,链表的长度增加n倍             。

尝试非数乘的情况:即当两个链表相乘时      ,用它们的数据域对应相乘的各个节点的值                   。

2                   、右乘法也要重载       ,否则右乘number*Node会报错                   ,加一行:__rmul__=__mul__      。

实例

def__mul__(self,other): iftype(other)isNode: n1,n2=self.values,other.values product=[p[0]*p[1]forpinzip(n1,n2)] returnNode.build(product) ifother<0ortype(other)isnotint: raiseTypeError("otherisanon-negetiveInteger") ifother==0:returnNode() ret=self.copy() for_inrange(1,other): self+=ret returnself __rmul__=__mul__ >>>a=Node()+range(1,3) >>>a*0 Node(None->None) >>>a*1 Node(1->2->None) >>>a*2 Node(1->2->1->2->None) >>>a*5 Node(1->2->1->2->1->2->1->2->1->2->None) >>> >>>3*a Node(1->2->1->2->1->2->None) >>>a Node(1->2->None) >>>a*=5 >>>a Node(1->2->1->2->1->2->1->2->1->2->None) >>> >>> >>>a=Node()+range(1,8) >>>b=Node(2)*7 >>>a*b Node(2->4->6->8->10->12->14->None) >>>b*a Node(2->4->6->8->10->12->14->None) >>>

以上就是python链表的乘法问题             ,希望对大家有所帮助       。更多Python学习指路:Python基础教程

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
ai自动生成ppt怎么用(Pyjs Python Javascript Compiler, Desktop Widget Set and RIA Web Framework)