Hi there,
This is my first post here…
I am a bit confused - I am going through the SingleLinkedList exercise in Learn More Python the Hard Way. I have managed to complete some of the tests but I can’t seem to update the count method
I have successfully run the shift and unshift methods… but problem lies with the following line… in the test program…
assert colors.pop() == "Cadmium Orange"
assert colors.count() == 1
My feeling is (and I know I could be wrong ) that the pop method does NOT remove the last element but does return the value…
This is the code that I have completed so far…
—BEGINNING OF CODE----------------------------
class Node(object):
def __init__(self, value, nxt):
self.value = value
self.next = nxt
def __repr__(self):
nval = self.next and self.next.value or None
return f"[{self.value}:{repr(nval)}]"
class SingleLinkedList(object):
def __init__(self):
self.begin = None
self.end = None
def push(self, obj):
node = Node(obj, None)
if self.begin is None:
self.begin = node
self.end = self.begin
else:
self.end.next = node
self.end = node
test_node = self.begin
while test_node:
test_node = test_node.next
def count(self):
"""Counts the number of elements in the list"""
node = self.begin
count = 0
while node:
count += 1
node = node.next
return count
def print_list(self):
cur_node = self.begin
while cur_node:
print(cur_node.value)
cur_node = cur_node.next
def pop(self):
if self.end == None: # this has to be adjusted -- if self.begin = None:
return None
elif self.end == self.begin:
node = self.begin
self.end = self.begin = None
return node.value
else:
node = self.begin
while node.next != self.end:
node = node.next
assert self.end != node
self.end = node
node = self.end
return node.next.value
def shift(self, data):
new_node = Node(data, None)
new_node.next = self.begin
self.end = self.begin
self.begin = new_node
def unshift(self):
"""Removes the first item and returns it"""
if self.begin == None:
return None
else:
self.end = self.begin
cur_node = self.end
print("This is cur_node UNSHIFT", cur_node)
self.begin = cur_node.next
print("THIS IS self.begin:", self.begin)
if cur_node:
return cur_node.value
cur_node = None
-----End of code------------------------------------------------
And this is the error I get when I run pytest…
colors.shift("Carbazole Violet")
assert colors.count() == 2
assert colors.pop() == "Cadmium Orange"
assert colors.count() == 1
E assert 2 == 1
E + where 2 = <bound method SingleLinkedList.count of <posted_zed.SingleLinkedList object at 0x7ff19d2597b8>>()
Basically the count is running and is maintained at 2 …
Can some one help?
Thank you in advance…
Vinay