The task is taken from LeetCode. I would appreciate an assessment of whether my coding style follows good practices, and if there are any habits or patterns you would find concerning when working together on a codebase.
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
My solution (Python3):
# Definition for singly-linked list provided by the platform.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# My solution
# (Leetcode doesn't really let you put things in an __init__ method in a defined way
# (we don't know if a new instance of Solution will be created for each test case),
# so I didn't have one).
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
self.sumHead: ListNode = ListNode(0)
self.sumLinkedList: ListNode = self.sumHead
self.carry: int = 0
while l1 and l2:
# both numbers still have digits
# Sanity Check
assert self.carry in [0, 1]
self.addDigitAndProcessCarry(l1.val + l2.val + self.carry)
# move to the next node for both numbers
l1 = l1.next
l2 = l2.next
# move to the next node for the sum
if l1 or l2 or self.carry:
self.sumLinkedList.next = ListNode(0)
self.sumLinkedList = self.sumLinkedList.next
for linkedListNotConsumed in [l1, l2]:
# only one linked list has more digits to be processed
while linkedListNotConsumed:
# Sanity Check
assert self.carry in [0, 1]
self.addDigitAndProcessCarry(linkedListNotConsumed.val + self.carry)
# move to the next node
linkedListNotConsumed = linkedListNotConsumed.next
if linkedListNotConsumed or self.carry:
self.sumLinkedList.next = ListNode(0)
self.sumLinkedList = self.sumLinkedList.next
if self.carry:
# Sanity Check
assert self.carry in [0, 1]
self.sumLinkedList.val = 1
return self.sumHead
def addDigitAndProcessCarry(self, value: int) -> None:
if value >= 10:
self.sumLinkedList.val = value - 10
self.carry = 1
else:
self.sumLinkedList.val = value
self.carry = 0