I am getting this error. I go through this concept but could not find the error. I am making a link list but when giving values it's showing me this error TypeError: DoubleLinkedList.add() takes 1 positional argument but 2 were givenI got through the below concept but I could not find the error or what to do. I am new in python programming
class Node:
def __init__(self, value):
self.next = None
self.prev = None
self.val = value
class DoubleLinkedList:
def __init__(self, ):
self.head = None
self.tail = None
self.size = 0
def add(self):
node = Node()
if self.tail is None:
self.head = node
self.tail = node
self.size = 1
else:
self.tail.next = node
node.prev = self.head
self.tail = node
self.size = 1
def __str__(self):
vals = []
node = self.head
while node is not Node:
vals.append(node.val)
node = node.next
return f"[{','.join((str(val) for val in vals))}]"
my_list = DoubleLinkedList()
my_list.add(1)
my_list.add(5)
my_list.add(2)
print(my_list)
```
CodePudding user response:
The reason why you see this error is because you only let add(self) to have one positional argument, which is self. What you want is something like follows:
def add(self, value):
node = Node(value)
if self.tail is None:
self.head = node
self.tail = node
self.size = 1
else:
self.tail.next = node
node.prev = self.head
self.tail = node
self.size = 1
Note that this answer doesn't look for your logic, only to fix your problem regarding positional arguments.
Also, self is a special keyword in Python used for instance variables and methods. When you create a new instance of Node as node = Node(), you automatically pass self argument, and the same goes for add method.
When you call my_list.add(1), Python inherently understands it as
my_list.add(self,1)
Of course, here self is equal to my_list. That's why Python tells you "I already got self, however, you've passed another value, so I will throw an error.
CodePudding user response:
You have to modify your add function like this
def add(self, value):
node = Node(value)
if self.tail is None:
self.head = node
self.tail = node
self.size = 1
else:
self.tail.next = node
node.prev = self.head
self.tail = node
self.size = 1
And you should modify a little also the __str__ function
def __str__(self):
vals = []
node = self.head
while node is not None:
vals.append(node.val)
node = node.next
return ','.join((str(val) for val in vals))

