I know StackOverflow isn't writing the question and getting the answer site but here is my problem from leetcode.
l1 = input()
l2 = input()
def f(x): #Gives reversed of linkedlist ex. [2, 4, 3] return 342
a, u = 0, 0
for ele in x:
if ele.isnumeric():
a = int(ele)*(10**u)
u = 1
return a
l = list(int(i) for i in str(f(l1) f(l2)))
print(list(reversed(l)))
This question is leet code problem so here I have solved the problem but this is something different they do not want spaces between the number after comma.
Input: [2,4,3] [5,6,4]
My output: [7, 0, 8]
Expected output: [7,0,8]
However, I also tried
k = str(f(l1) f(l2))
print("[" ",".join(str(k)[::-1]) "]")
CodePudding user response:
You aren't supposed to use input() and print() on leetcode
When you start a problem they give you a function you have to fill and return the result.
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
#put your code here
return the_result
This problem is supposed to use a linked list with nodes defined as
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
this is what should be the input of the addTwoNumbers()
method you are supposed to code.
But somehow by using input()
you are bypassing this and grabbing the raw list.
Also, prints(stdout) are not what is being evaluated by the leetcode system, they look for the output of addTwoNumbers()
which in this case is blank.
CodePudding user response:
That is just the default representation of a list, it has a space after each comma
x = [1, 2, 3]
print(x) # [1, 2, 3] type is list
print(str(x).replace(" ", "")) # [1,2,3] type is str
CodePudding user response:
Here is the complete solution;
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def __init__(self):
self.head = None
def rev(self, ls):
res = []
self.head = ls
while self.head:
res.append(str(self.head.val))
self.head = self.head.next
return list(reversed(res))
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res1 = int(''.join(self.rev(l1)))
res2 = int(''.join(self.rev(l2)))
res3 = str(res1 res2)
resls = list(reversed([i for i in res3]))
self.head = ListNode(resls[0], None)
finalres = self.head
for i in range(1, len(resls)):
lsn = ListNode(resls[i], None)
finalres.next = lsn
finalres = finalres.next
return self.head