I am doing an assignment and it is not going very well. It is my code which is not working super good:
from dataclasses import dataclass
@dataclass
class Node:
value: int = None
nxt: Node = None
@dataclass
class Deque:
head: Node = None # First node in queue
tail: Node = None # Last node in queue
size: int = 0
def add_first(self, n):
new = Node(n, None)
if self.head is None:
self.head = new
self.tail = new
self.size = 1
s = "{ "
node = self.head
while node is not None:
s = str(node.value) " "
node = node.nxt
s = "}"
return s
def add_last(self, n):
new = Node(n, None)
if self.head is None:
self.head = new
self.tail = new
else:
self.tail.nxt = new
self.tail = new
self.size = 1
def get_last(self):
if self.tail is None:
print("Get can't be applied on an empty list")
return None
else:
return self.tail.value
def get_first(self):
if self.head is None:
print("Get can't be applied on an empty list")
return None
else:
#node = self.head
return self.head.value
def remove_first(self):
if self.head is None:
print("Remove can't be applied on an empty list")
elif self.head == self.tail:
s = self.head.value
self.head = None
self.tail = None
self.size -= 1
return s
elif self.size == 1:
node = self.head
self.head = self.head.nxt
self.size -= 1
return node.value
Output: { 1 2 3 4 5 6 7 8 9 10 } Size: 10 { 20 19 18 17 16 15 14 13 12 11 1 2 3 4 5 6 7 8 9 10 } Size: 20
Update: I found an answer to my question. It was issues regarding def add_first and def remove last as well as def remove first.
CodePudding user response:
Because this is homework I'm not going to give away the fixed code, but I will point out what needs fixing. I believe I figured out all the required fixes, but I could be wrong since you didn't share the code used to test your Deque:
- Your
add_firstmethod is unnecessarily stepping through all the Nodes, then setting the last Node (thetail)'snxtvalue to the new Node, meaning the new Node will appear at the end of the Deque. Instead, all you need to do is set thenxtof the new Node to the currenthead, and setheadto the new Node. - Your
remove_firstdoesn't account for any case except if there's one Node in the Deque. You have to set the Deque'sheadto its oldhead'snxtNode in all other cases. - Your
remove_lastalso doesn't account for any case except if there's one Node in the Deque. In all other cases, you have to loop through the Deque's Nodes, starting withhead, until you find a Node whosenxtvalue is the Deque'stail, then set itsnxtto None, and set the Deque'stailto that Node.
Example of finding the Node before thetailNode:node = self.head while node.nxt != self.tail: node = node.nxt node.nxt = None self.tail = node
