# -*- coding: utf-8 -*-
# MIT OCW 6.189 Homework 3
# Exercise 3.6 – Your First Class
# Mechanical MOOC
# Judy Young
# July 26, 2013
# This exercise, plus the remaining written questions (3.10 - 3.11) will be the start
# of our journey into object-oriented programming; we suggest you do these written
# exercises before tackling this question.
# For this exercise, you will be coding your very first class, a Queue class.
# Queues are a fundamental computer science data structure. A queue is basically
# like a line at Disneyland - you can add elements to a queue, and they maintain
# a specific order. When you want to get something off the end of a queue, you get
# the item that has been in there the longest (this is known as ‘first-in-first-out’,
# or FIFO). You can read up on queues at Wikipedia if you’d like to learn more.
# Create a new file called queue.py to make your Queue class.
# In your Queue class, you will need three methods:
# • init : to initialize your Queue (think: how will you store the queue’s elements?
# You’ll need to initialize an appropriate object attribute in this method)
# • insert: inserts one element in your Queue
# • remove: removes one element from your Queue and returns it.
# If the queue is empty, return a message that says it is empty.
class Queue(object):
def __init__(self):
self.elements = ""
def insert(self, element):
self.elements += element
print "...", element, "added"
# return "\n", element, "has been added to the end of this queue"
def remove(self):
if len(self.elements) == 0:
return "\nThis Queue is empty"
else:
element_to_remove = self.elements[0]
self.elements = self.elements[1:]
return "\n" + element_to_remove + ", the first/oldest item in this Queue has been removed"
# let's see what it looks like to add and remove elements
my_queue = Queue()
print "my_queue =", my_queue.elements
print my_queue.remove()
print "\nAdding some elements ..."
my_queue.insert("a")
my_queue.insert("b")
my_queue.insert("c")
my_queue.insert("d")
print "my_queue =", my_queue.elements
print my_queue.remove()
print "my_queue =", my_queue.elements
print "\nAdding some elements ..."
my_queue.insert("e")
my_queue.insert("f")
my_queue.insert("g")
print "my_queue =", my_queue.elements
print my_queue.remove()
print "my_queue =", my_queue.elements
print my_queue.remove()
print my_queue.remove()
print my_queue.remove()
print my_queue.remove()
print my_queue.remove()
print my_queue.remove()