Implement a Stack (FILO)

``````

In [46]:

class Stack:
def __init__(self):
self.items = []

def __str__(self):
string = ""
if len(self.items) != 0:
for i in xrange(len(self.items)-1, -1, -1):
string += "{0}\n".format(self.items[i])
return string

def pop(self):
if self.items != []:
return self.items.pop()
else:
return None

def push(self, item):
self.items.insert(0, item)

def peek(self):
return self.items[-1]

``````
``````

In [47]:

stack = Stack()
print(stack)
stack.push(1)
print(stack)
stack.push(2)
print(stack)
stack.push(3)
print(stack)
print("Peeking at {0}".format(stack.peek()))
print("Popped off {0}".format(stack.pop()))
print(stack)

``````
``````

1

1
2

1
2
3

Peeking at 1
Popped off 1
2
3

``````

Implement a Queue (FIFO)

``````

In [55]:

class Queue:
def __init__(self):
self.items = []

def __str__(self):
string = ""
for item in self.items:
string += "{0}\n".format(item)
return string

def enqueue(self, item):
self.items.append(item)

def dequeue(self):
if self.items != []:
return self.items.pop(0)
else:
return None

``````
``````

In [56]:

queue = Queue()
print(queue)
queue.enqueue(1)
print(queue)
queue.enqueue(2)
print(queue)
queue.enqueue(3)
print(queue)
queue.dequeue()
print(queue)

``````
``````

1

1
2

1
2
3

2
3

``````
``````

In [49]:

``````