0

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
1
  • can you post the rest of the class' code? Commented Aug 10, 2020 at 2:41

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I knew it was raise I just didn't realise I had written return instead of raise. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.