CC189 - Cracking the Coding Interview

Chapter 3


In [1]:
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals

Implementing a Stack


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

    def isEmpty(self):
        return self.items == []

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

    def pop(self):
        return self.items.pop()

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

    def size(self):
        return len(self.items)

In [32]:
s = Stack()
print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())


True
dog
3
False
8.4
True
2

Implementing a Queue


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

    def isEmpty(self):
        return self.items == []

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

    def remove(self):
        if len(self.items) > 0:
            self.items = self.items[1:] 

    def peek(self):
        return self.items[0] if len(self.items) > 0 else False

    def size(self):
        return len(self.items)

Python deque


In [2]:
from collections import deque

In [9]:
q = deque([1, 3, 2, 5])

In [10]:
q


Out[10]:
deque([1, 3, 2, 5])

In [11]:
q.append(8)
q


Out[11]:
deque([1, 3, 2, 5, 8])

In [14]:
q.count(3)


Out[14]:
1

In [15]:
len(q)


Out[15]:
5

In [18]:
q.pop()
q


Out[18]:
deque([1, 3, 2, 5])

In [19]:
q.popleft()
q


Out[19]:
deque([3, 2, 5])

In [23]:
q.extend('abc')

In [24]:
q


Out[24]:
deque([3, 2, 5, 'a', 'b', 'c'])

In [25]:
q.extendleft('def')

In [26]:
q


Out[26]:
deque(['f', 'e', 'd', 3, 2, 5, 'a', 'b', 'c'])

In [ ]:

3.1 Three in One


In [ ]: