In the past two episodes in this series, we defined a Node
class, complete with __init__
and __str__
methods. However, we came across a bug, and now it's time to squash it.
To remind you of the problem, here's the current code for printing a Node.
# indented within Node() class.
def __str__(self):
s = "Node with value {} and next node: {}.".format(self.value, self.next_node)
return s
Do you see the problem? (I didn't.)
To give you an idea, here's a the result of printing the first node in a list of five nodes.
Node with value 14 and next node: Node with value 27 and next node: Node with value 33 and next node: Node with value 72 and next node: Node with value 38 and next node: None.....
That's a mess. Now do you see what happened? It's the bug at work. It recursively printed all of the nodes in the list. This probably isn't the way we want to print a single node!
At any rate, I wanted to print only the Node's value and the value of the next Node. How can we do that? Here is my solution.
# indented within Node() class.
def __str__(self):
s = "Node with value {} and ".format(self.value)
if not self.next_node:
s += "no next node"
else:
s += "next node has value {}.".format(self.next_node.value)
return s
Note that I needed the if/else
logic because other otherwise, cases where text node's next value is None
, self.next_value.value
would effectively be calling None.value
, which triggers the following type of error.
AttributeError: 'NoneType' object has no attribute 'value'
So that's the first bug of the series fixed.
Next it's on to defining a SinglyLinkedList
, but save the reason why for the next post.
The code for this project is available here on GitHub. I'll be updating it gradually as I write this series. I'll be sure to commit at least as often as I post, so you can back up and see that code as it was when I published a given post.
Top comments (0)