Leetcode 2. Add Two Numbers —> Syntax error?

Question:

I am working on 2nd problem from Leetcode (Add two numbers):

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

I have wrote my code in my desktop PyCharm app, and it does not show any syntax errors whatsoever, but when I upload my solution to Leetcode its compiler suggests that there is syntax error in line 8.

That’s what I have:

class ListNode(object):
    def _init_(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution(object):

    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:

        added = ListNode(val=(l1.val + l2.val) % 10)
        carry_over = (l1.val + l2.val) // 10
        current_node = added

        while (l1.next and l2.next):
            l1 = l1.next
            l2 = l2.next

            current_node.next = ListNode(val=(carry_over + l1.val + l2.val) % 10)
            carry_over = (carry_over + l1.val + l2.val) // 10
            current_node = current_node.next

        while (l1.next):
            l1 = l1.next
            current_node.next = ListNode(val=(carry_over + l1.val) % 10)
            carry_over = (carry_over + l1.val) // 10
            current_node = current_node.next

        while (l2.next):
            l2 = l2.next
            current_node.next = ListNode(val=(carry_over + l2.val) % 10)
            carry_over = (carry_over + l2.val) // 10
            current_node = current_node.next

        if carry_over > 0:
            currentnode.next = ListNode(val=1)

        return(added)

Could you please let me know what might have gone wrong?

Asked By: ChrisQ267

||

Answers:

The syntax error on line 8 however is due to the : character is used in type hints to indicate the type of a variable or function parameter. However, type hints were only introduced in Python 3.5, and are not supported in earlier versions. If you are using a version of Python earlier than 3.5, you should remove the : characters from the function definition. Here is the corrected code:

def addTwoNumbers(self, l1, l2):

and change

if carry_over > 0:
        currentnode.next = ListNode(val=1)

to:

if carry_over > 0:
        current_node.next = ListNode(val=1)
Answered By: dash
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.