千家信息网

python链表之乘法问题的示例分析

发表于:2025-11-11 作者:千家信息网编辑
千家信息网最后更新 2025年11月11日,这篇文章将为大家详细讲解有关python链表之乘法问题的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。说明1、左乘法约定为数乘,即乘以整数n,链表的长度增加
千家信息网最后更新 2025年11月11日python链表之乘法问题的示例分析

这篇文章将为大家详细讲解有关python链表之乘法问题的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

说明

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

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

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

实例

   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 * 0Node(None->None)>>> a * 1Node(1->2->None)>>> a * 2Node(1->2->1->2->None)>>> a * 5Node(1->2->1->2->1->2->1->2->1->2->None)>>>>>> 3 * aNode(1->2->1->2->1->2->None)>>> aNode(1->2->None)>>> a *= 5>>> aNode(1->2->1->2->1->2->1->2->1->2->None)>>>>>>>>> a = Node() + range(1,8)>>> b = Node(2) * 7>>> a * bNode(2->4->6->8->10->12->14->None)>>> b * aNode(2->4->6->8->10->12->14->None)>>>'''

关于"python链表之乘法问题的示例分析"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

0