Python for the win


  • 24

    Python supports arbitrarily large integers, so I can safely turn the two lists into ints, add them, and turn the sum into a list.

    class Solution:
        def addTwoNumbers(self, l1, l2):
            def toint(node):
                return node.val + 10 * toint(node.next) if node else 0
            def tolist(n):
                node = ListNode(n % 10)
                if n > 9:
                    node.next = tolist(n / 10)
                return node
            return tolist(toint(l1) + toint(l2))
    

    Iterative tolist instead of recursive:

    class Solution:
        def addTwoNumbers(self, l1, l2):
            def toint(node):
                return node.val + 10 * toint(node.next) if node else 0
            n = toint(l1) + toint(l2)
            first = last = ListNode(n % 10)
            while n > 9:
                n /= 10
                last.next = last = ListNode(n % 10)
            return first
    

    And a very different solution that could sum arbitrarily many addends, not just two:

    class Solution:
        def addTwoNumbers(self, l1, l2):
            addends = l1, l2
            dummy = end = ListNode(0)
            carry = 0
            while addends or carry:
                carry += sum(a.val for a in addends)
                addends = [a.next for a in addends if a.next]
                end.next = end = ListNode(carry % 10)
                carry /= 10
            return dummy.next

  • 1
    Z

    It is always a pleasure to see your code. It concludes my searching of better solution. :P


  • 1

    Nice code but I guess the interviewer would've wanted you not to copy the lists into additional arrays...


  • 0
    B

    Can someone explain the chain assignment here?

    last.next = last = ListNode(n % 10)   
    

    It seems what it does is

    last.next  = ListNode(n % 10)
    last = last.next 
    

    Why would chain assignment work in this way? I thought it would do something like

    last.next  = ListNode(n % 10)
    last = ListNode(n % 10) 
    

    Thanks!


  • 0
    M

    @bojose The chained assignment works as following: tmp = ListNode(n % 10); last.next = tmp; last = tmp;
    The last assignment came after the second assignment, therefore overwrite last.next as none.
    What you perceived is that they hold different reference and therefore can't guarantee the variable last proceed to be last.next.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.