Deques also have size() and is_empty() methods, just like the other data structures in this course. The size() method returns the number of items in the deque, and the is_empty() method returns a Boolean value describing whether or not the deque is empty. Learn how to implement each of these methods in your deque class in this video.
- Let's code our last two methods for the deque class, the size method and the isEmpty method. These are logically identical to the size and isEmpty methods that you might use for a stack or a queue. For the size method all we need to do is find the length of the list that is representing our deque, and to do that we can use Python's built-in length method. So we'll simply say "Return the length of self.items." Even if Items is an empty list, this will still return zero for us, rather than erroring out.
For the isEmpty method, all we need to do is compare self.items to an empty list and return that value. What this expression should give us is a bullion. A note here we need to use double-equals, not single-equals. So if self.items is an empty list, this should evaluate to true, and if self.items is not an empty list, this should evaluate to false.
Let's save this and try this out in the terminal. I'll create our own deque object. And let's try this new isEmpty method now that we've just created the object and haven't added anything to it yet. Cool, so we get true, which is what we would expect. If I go ahead and add something, we should get false if we run that isEmpty method again. So let's add apple, and then let's call the isEmpty method, and we get false, great.
So that works exactly as we expect. At this point if if do my_D.size, I should get one because we've only added one thing to our deque, and that's what I get. Let's go back to the code, and create our last couple doc strings here. The size method simply returns the length of the list, which is representing the deque. The run time will be constant, because all we're doing is finding the length of a thing and returning it.
Now we come down to the isEmpty method, and in summary what this is doing is it's checking to see whether or not Items is an empty list. Checks to see if the list representing our deque is empty, and it returns true if so, or false if it isn't. The runtime here is also constant, because all we're doing is running a bullion check and returning that value.
And now our whole entire deque class has been coded.
- Abstract types and data structures
- Stacks as a linear abstract data type
- Creating the Stack class and its methods
- Adding items to the top and bottom of a stack
- Creating the Queue class and its methods
- Manipulating items in a queue
- Creating the Dequeue class and its methods
- Adding and removing items from a dequeue