aboutsummaryrefslogtreecommitdiff
path: root/shunting.py
blob: 22d79f115d879ad0e723fef5313d038eca92d2dc (plain)
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
precedence = {
    '-': 0,
    '+': 0,
    '*': 1,
    '/': 1,
}


def shunting(inss: [str]):
    op = []
    out = []
    for ins in inss:
        if str.isnumeric(ins):
            list.append(out, ins)
        elif len(ins) == 1 and ins in "+-*/":
            p = precedence[ins]
            while op:
                l = op[len(op) - 1]
                if l == "(":
                    break
                pl = precedence[l]
                if pl > p:
                    out.append(op.pop())
                else:
                    break
            op.append(ins)
        elif len(ins) == 1 and ins in "mkbt":
            out.append(ins)
        elif ins == "(":
            op.append(ins)
        elif ins == ")":
            while True:
                if not op:
                    raise "ILLEGAL PARENTHESIS"
                l = op.pop()
                if l == "(":
                    break
                out.append(l)
        else:
            raise f"UNKNOWN OP {ins}"
    while op:
        l = op.pop()
        if l == "(":
            raise "ILLEGAL PARENTHESIS"
        out.append(l)
    return out


print(shunting("1 + 22 k * ( 3 + 4 ) k".split()))