about summary refs log tree commit diff
path: root/users/wpcarro/scratch/facebook/infix-to-postfix.py
blob: 4c6d64494d959b30e79281f56b643fb440af4890 (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
50
51
operators = {
    '*': 1,
    '+': 0,
}

def tokenize(xs):
    result = []
    i = 0
    while i < len(xs):
        current = xs[i]
        if current in operators.keys():
            result.append(current)
            i += 1
            continue
        else:
            i += 1
            while i < len(xs) and xs[i] in {str(n) for n in range(10)}:
                current += xs[i]
                i += 1
            result.append(int(current))
    return result

def postfix(xs):
    result = []
    s = []
    for x in xs:
        if x in operators.keys():
            while s and operators[s[-1]] >= operators[x]:
                result.append(s.pop())
            s.append(x)
        else:
            result.append(x)
    while s:
        result.append(s.pop())
    return result

def evaluate(xs):
    s = []
    for x in xs:
        print(s, x)
        if x == '*':
            s.append(s.pop() * s.pop())
        elif x == '+':
            s.append(s.pop() + s.pop())
        else:
            s.append(x)
        print(s)
    return s[-1]


print(evaluate(postfix(tokenize("12+3*10"))))