about summary refs log tree commit diff
path: root/users/wpcarro/scratch/facebook/largest-stack.py
blob: 052db44153d46fa233b1f22020c113ec4885af41 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from stack import Stack, from_list
from heapq import heapify, heappush, heappop
from random import shuffle

class MaxStack(Stack):
    def __init__(self):
        self.max = Stack()
        super().__init__()

    def __repr__(self):
        return super().__repr__()

    def push(self, x):
        super().push(x)
        max = self.get_max()
        if not max:
            self.max.push(x)
        else:
            self.max.push(max if x < max else x)

    def pop(self):
        self.max.pop()
        return super().pop()

    def get_max(self):
        return self.max.peek()

xs = list(range(1, 11))
shuffle(xs)
stack = MaxStack()
for x in xs:
    stack.push(x)

print(stack)
result = stack.get_max()
print(result)
assert result == 10

popped = stack.pop()
print("Popped: {}".format(popped))
print(stack)
while popped != 10:
    assert stack.get_max() == 10
    popped = stack.pop()
    print("Popped: {}".format(popped))
    print(stack)

assert stack.get_max() != 10
print("Success!")