溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python鏈表的乘法問(wèn)題怎么解決

發(fā)布時(shí)間:2022-05-27 14:56:41 來(lái)源:億速云 閱讀:145 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹了python鏈表的乘法問(wèn)題怎么解決的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇python鏈表的乘法問(wèn)題怎么解決文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

說(shuō)明

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)
>>>
'''

關(guān)于“python鏈表的乘法問(wèn)題怎么解決”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“python鏈表的乘法問(wèn)題怎么解決”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI