Cracking The Code Interview Ch 3.1


In [ ]:
class StackOfThree:
    def __init__(self, size):
        self.list = [None] * size
        self.start = [0, int(size/3), int(2*size/3)]
        self.position = [0, int(size/3), int(2*size/3)]

    def push(self, stackId, element):
        
        if stackId not in [0,1,2]:
            raise Exception('bad stackId')
        if self.position[stackId] >= len(self.list) or self.position[stackId] == self.start[stackId + 1]:
            raise Exception('cannot exceed stack size')
        
        self.list[self.position[stackId]] = element
        self.position[stackId] += 1
        
    def pop(self, stackId):
        
        if stackId not in [0,1,2]:
            raise Exception('bad stackId')
        if self.size(stackId) == 0:
            raise Exception('stack is empty')
        
        self.position[stackId] -= 1
        return self.list[self.position[stackId]]
        
       
    def size(self, stackId):
        if stackId not in [0, 1, 2]:
            raise Exception("bad stackId")
        return self.position[stackId] - self.start[stackId]

In [ ]:
stacks = StackOfThree(10)

In [ ]:
print(stacks.size(0))
print(stacks.size(1))
print(stacks.size(2))

In [ ]:
stacks.push(0, 12345)
stacks.push(0, 714)
stacks.push(0, 314)
print(stacks.size(0))
stacks.push(0, 5)
stacks.push(0, 10)
print(stacks.size(0))

In [ ]:
print(stacks.pop(0))
print(stacks.pop(0))
print(stacks.pop(0))

In [ ]: