新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python鏈表的乘法問題
說明

1、左乘法約定為數(shù)乘,即乘以整數(shù)n,鏈表的長(zhǎng)度增加n倍。
嘗試非數(shù)乘的情況:即當(dāng)兩個(gè)鏈表相乘時(shí),用它們的數(shù)據(jù)域?qū)?yīng)相乘的各個(gè)節(jié)點(diǎn)的值。
2、右乘法也要重載,否則右乘number*Node會(huì)報(bào)錯(cuò),加一行:__rmul__=__mul__。
實(shí)例
def __mul__(self, other):
if type(other) is Node:
n1,n2 = self.values,other.values
product = [p[0]*p[1] for p in zip(n1,n2)]
return Node.build(product)
if other<0 or type(other) is not int:
raise TypeError("other is a non-negetive Integer")
if other==0:return Node()
ret = self.copy()
for _ in range(1,other):
self += ret
return self
__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鏈表的乘法問題,希望對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
文章題目:創(chuàng)新互聯(lián)Python教程:python鏈表的乘法問題
文章源于:http://www.dlmjj.cn/article/dpohsoo.html


咨詢
建站咨詢
