I'm trying to understand why I get different output when I run the code on leetcode and in VSC. I solved the problem "Add Two Numbers" in Python with the following code:
from types import NoneType
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
str_l1=""
str_l2=""
if type(l1.val) is int:
my_l1=[l1.val]
elif type(l1.val) is NoneType:
my_l1=[0]
else:
my_l1=l1.val
if type(l2.val) is int:
my_l2=[l2.val]
elif type(l2.val) is NoneType:
my_l2=[0]
else:
my_l2=l2.val
for i in range(len(my_l1)):
str_l1+=str(my_l1[len(my_l1)-i-1])
for i in range(len(my_l2)):
str_l2+=str(my_l2[len(my_l2)-i-1])
num_l1=int(str_l1)
num_l2=int(str_l2)
somma=num_l1+num_l2
str_somma=str(somma)
list_somma=[]
for i in range(len(str_somma)):
list_somma.append(int(str_somma[len(str_somma)-i-1]))
sol=ListNode(list_somma)
return sol
And this is the example:
my_solution=Solution()
x=my_solution.addTwoNumbers(ListNode([2,4,3]),ListNode([5,6,4]))
print(x.val)
When I run the code in VSC I get the correct output [7,0,8], while when I run it in leetcode with the same input I get the wrong output [[7]]. How is that possible?
[7, 0, 8]isinstance(l1.val, int)but forNoneI would useis- likeelif l1.val is None:str_somma[-i-1]instead ofstr_somma[len(str_somma)-i-1]. But you could simply usereversed(my_l1)and run withoutrange()andlen()likefor item in reversed(my_l1): str_l1 += str(item)