Grand Skunk
Grand Skunk

Reputation: 39

Implementing a linked list using Queues: Python

I'm trying to implement a queue using linked lists. It mostly works however I think there is a problem at my is_empty function, because when I run the code and try to dequeue when there's nothing in the queue, it should say IndexError("Can't dequeue from empty queue.") but my tests tell me it returned nothing

The test:

Failed example:
    result = q.dequeue()
Expected:
    Traceback (most recent call last):
    ...
    IndexError: Can't dequeue from empty queue.
Got nothing

The code for dequeue and is_empty functions:

def dequeue(self):
               
        if self.is_empty(): 
            return IndexError("Can't dequeue from empty queue.")
        else:
            to_return = self.head.item
            self.head = self.head.next_node
            return to_return
        

    def is_empty(self):
        """ returns True if the queue is empty """
        return self.head is None

Upvotes: 0

Views: 119

Answers (1)

Smurphy0000
Smurphy0000

Reputation: 76

If you are expecting to throw the error, use the raise statement instead of return

Here is sample code:

class Queue():
    def __init__(self):
        self.head = None

    def dequeue(self):
        if self.is_empty(): 
            raise IndexError("Can't dequeue from empty queue.")
        else:
            to_return = self.head.item
            self.head = self.head.next_node
            return to_return
        
    def is_empty(self):
        """ returns True if the queue is empty """
        return self.head is None

queue = Queue()

item = queue.dequeue()

print(item)

Output:

Traceback (most recent call last):
  File "test2.py", line 20, in <module>
    item = queue.dequeue()
  File "test2.py", line 8, in dequeue
    raise IndexError("Can't dequeue from empty queue.")
IndexError: Can't dequeue from empty queue.

Upvotes: 1

Related Questions