• 技术文章 >Python技术 >Python基础教程

    python链表的乘法问题

    小妮浅浅小妮浅浅2021-09-10 09:20:29原创2640

    说明

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

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

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

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

       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链表的乘法问题,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python链表
    上一篇:python如何解决黏包问题 下一篇:python链表实现左移和右移

    相关文章推荐

    • Python yield关键字的应用限制• Python yield实现迭代器协议• python列表删除项目的方法• Python删除列表中的非字母字符• python创建实例中类属性的变化• python默认参数的使用注意• python变长参数的使用注意• python变长参数的使用场景• python建立文本文件的两种途径• python多行读写的操作

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网