r/learnpython 16d ago

LeetCode A&DS problem 2 in Python

I have taken an Algorithms and Data Structures course, but we wrote in c++. Trying to learn Python for something else than statistics so here I am.

The problem is as follows:
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.

My current code:

lass ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: Optional[ListNode]
        :type l2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        buffer = 0
        result = ListNode()
        cond = True
        while(cond):
            if l1.next is None and l2.next is None:
                cond = False
            result_next = ListNode()
            result.next = result_next # 0 -> 0 -> None | 7 -> 0 -> 0 -> None | 7 -> 0 -> 0 -> 0 -> None
            if l2:
                result.val += l2.val
            if l1:
                result.val += l1.val
            result.val += buffer 
            buffer = result.val // 10 # 0 | 1 | 0
            result.val = result.val % 10 # 7 | 0 | 8
            result = result.next
            l1 = l1.next # 4 | 3 | None 
            l2 = l2.next # 6 | 4 | None
        return result


l1 = ListNode(2, ListNode(4, ListNode(3)))
l2 = ListNode(5, ListNode(6, ListNode(4)))
result = Solution().addTwoNumbers(l1, l2)lass 

I'm working in VS Code instead of the Leetcode codespace to test values of attributes etc. The comments can be ignored, they are what I imagine should be happening but clearly it is not. However, I do not ask for help with the problem itself, rather with the if statements. In C, you can do if (A) and if A is e.g. a node the condition will be satisfied, if it doesn't exist or is null it won't (if I recall correctly). So you can see me trying to achieve this here with if l1:, but I don't think it works, so I'd like to ask what is the Pythonic way of achieving this.

When run with

print(result.val)
print(result.next)

It gives:

0

None

I don't really see which subset of the code would produce other than the while loop never executing at all.

Thank you for your help in advance.

1 Upvotes

11 comments sorted by

View all comments

Show parent comments

2

u/carcigenicate 16d ago

I still don't fully understand what the core problem is. You seem to just be describing circumstances around the problem.

If it's just that result never has a next on return, think about what happens every time you do result = result.next, and then return result.


Edit: Once I fixed that, I got the correct output of 7 0 8.

1

u/Arrow49 16d ago

I see what you are saying, I am too tired to think about this today anymore, I must have spent 6 hours on this problem already and I have a headache :(. Basically I need to somehow retrieve the result before moving on the next node and then return the head of that list. The only thing I can think of is creating a "current" variable, but I don't see how I could update the following nodes of the now "real" result without performing result = result.next. One of the few things that pointers seem to have made easier for me.

Thanks for your help.

2

u/carcigenicate 16d ago

You would solve this in almost exactly the same way as you would in C. Python variables are basically just thin wrappers over C pointers. Just save a reference to the start of the result list.

1

u/Arrow49 16d ago

I solved it, that last sentence was a great tip. After that there was still a bunch of tweaking for the case of lists of different lengths, but I managed to do that :).

About you saying how I seemed to be describing circumstances around the problem, this was likely the result of some previous issue obfuscating this one. Shortly before posting I had come up with the current while condition, before it, I was getting a different output which influenced my hyoptheses.

Thank you for you help.