Home > Software design >  self and arguments transmission in python
self and arguments transmission in python

Time:09-17

I have a code:

class ListNode:
     def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
class Solution(object):
     def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
         dummy = cur = ListNode(0)
         carry = 0
         while l1 or l2 or carry:
             if l1:
                 carry  = l1.val
                 l1 = l1.next
             if l2:
                 carry  = l2.val
                 l2 = l2.next
             cur.next = ListNode(carry%10)
             cur = cur.next
             carry //=10
         return dummy.next
l1 = [2, 4, 3]
l2 = [5, 6, 4]
print(Solution.addTwoNumbers(l1, l2))

but it's not working, What I should to do to make it work? It writes that addTwoNumbers() missing 1 required positional argument.(I dont wanna add "def add" in class Listnode)

CodePudding user response:

The "Pythonic" fix here is to remove the Solution class. This is a pretty common convention in Java (where everything has to be explicitly defined as an object class) but it's completely unnecessary in Python.

class ListNode:
    def __init__(self, val=0, next=None) -> None:
        self.val = val
        self.next = next

    def __repr__(self) -> str:
        repr = f"ListNode<{self.val}"
        n = self.next
        while n is not None:
            repr  = f", {n.val}"
            n = n.next
        repr  = ">"
        return repr


def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
    dummy = cur = ListNode(0)
    carry = 0
    while l1 or l2 or carry:
        if l1:
            carry  = l1.val
            l1 = l1.next
        if l2:
            carry  = l2.val
            l2 = l2.next
        cur.next = ListNode(carry % 10)
        cur = cur.next
        carry //= 10
    return dummy.next


def addTwoLists(l1: list, l2: list) -> list:
    ret = []
    carry = 0
    for i1, i2 in zip(l1, l2):
        ret.append(i1   i2   carry)
        carry = 0
        if ret[-1] >= 10:
            carry = 1
            ret[-1] -= 10
    if carry:
        ret.append(carry)
    return ret
    # alternate one-line implementation: return list(reversed(str(int(''.join(map(str, reversed(l1))))   int(''.join(map(str, reversed(l2)))))))


n1 = ListNode(2, ListNode(4, ListNode(3)))
n2 = ListNode(5, ListNode(6, ListNode(4)))
print(addTwoNumbers(n1, n2))

l1 = [2, 4, 3]
l2 = [5, 6, 4]
print(addTwoLists(l1, l2))
  • Related