I am very beginner in coding, can you help me understand the error
I am giving the parameter still the error says required 1 positional argument
Input(l1 and l2 are linked list)
l1=[2,4,3]
l2=[5,4,6]
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def inttolist(self, i) -> ListNode:
while(i%10!=0):
self = ListNode(i%10, inttolist(int(i/10)))
return self
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a,b,c,d=l1,l2,1,0
while(a!=None):
d=d+(a.val+b.val)*c
a,b=a.next,b.next
c=c*10
print(d)
self = Solution.inttolist(int(d))
return self
Error code
TypeError: inttolist() missing 1 required positional argument: 'i'
self = Solution.inttolist(int(d))
Line 18 in addTwoNumbers (Solution.py)
ret = Solution().addTwoNumbers(param_1, param_2)
Line 45 in _driver (Solution.py)
_driver()
Line 56 in <module> (Solution.py)
The problem is the misuse of the self
variable. the self
argument is a variable containing the instantiated Solution
class. There are two problems with that:
Solution.inttolist(int(d))
, should be called using:self.inttolist(int(d))
.self
value, create a new variable for that instead, so we have to change this:self = ListNode(i%10, inttolist(int(i/10)))
.Below I added a working solution, in case you are still stuck after applying the above changes.
The input asks for a ListNode, so I converted your input list to their specifications using:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def generate_link_list(l1: list):
nodes = []
for val in l1:
def generate_link_list(l1: list):
nodes = []
for val in l1:
nodes.append(ListNode(val))
for index, node in enumerate(nodes[:-1]):
node.next = nodes[index + 1]
return nodes[0]
l1 = generate_link_list(l1)
l2 = generate_link_list(l2)
With the above changes the code will become:
class Solution:
def inttolist(self, i) -> ListNode:
ans = 0 # <--- the new variable, instead of `self`
while (i % 10 != 0):
ans = ListNode(i % 10, self.inttolist(int(i / 10)))
return ans
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a, b, c, d = l1, l2, 1, 0
while (a != None):
d = d + (a.val + b.val) * c
a, b = a.next, b.next
c = c * 10
print(d)
ans = self.inttolist(int(d))
return ans
Running:
print(Solution().addTwoNumbers(l1, l2))
Will result in the answer: 987
, which is the sum of the two lists, when you reverse their values and concatenate them.