Skip to content

Instantly share code, notes, and snippets.

@AO8
Created December 18, 2018 16:53
Show Gist options
  • Select an option

  • Save AO8/bba0f7bed170a6537e4be1b8cdd3a918 to your computer and use it in GitHub Desktop.

Select an option

Save AO8/bba0f7bed170a6537e4be1b8cdd3a918 to your computer and use it in GitHub Desktop.
Queue practice with Python 3.
# Exercise completed as part of Erin Allard's Lynda.com course,
# 'Python Data Structures: Stacks, Queues, and Deques'
class Queue:
"""An ADT that stores items in the order in which they
were added. Items are added to the back and removed
from the front - FIFO.
"""
def __init__(self):
self.items = []
def enqueue(self, item):
"""Takes in an item and inserts that item into the zeroeth
index of the list that is representing the Queue.
The runtime is 0(n), or linear time, because inserting into
the zeroeth index of a list forces all other items to move
one index to the right.
"""
self.items.insert(0, item)
def dequeue(self):
"""Removes and returns the front most item from Queue, which
is represented by the last item in list.
The runtime is 0(1), or constant time, because indexing to
the end of a list happens in constant time.
"""
if self.items:
return self.items.pop()
else:
return None
def peek(self):
"""Returns the last item in list, which represents the font
most item in the Queue.
The runtime is 0(1), or constant time, because indexing the
last item in a list happens in constant time.
"""
if self.items:
return self.items[-1]
else:
return None
def size(self):
"""Returns size of Queue, which is represented by the length
of the list.
The runtime is 0(1), or constant time, because returning list
length happens in constant time.
"""
return len(self.items)
def is_empty(self):
"""Returns Boolean value expressing wheter or not the list
representing Queue is empty.
A simple check for equality happens in 0(1), or constant time.
"""
return self.items == []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment