NUMBERS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] OPERATORS = ["-", "*"] class Number: def __init__(self, n): self.n = n def __str__(self): return str(self.n) class Mul: def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return "(%s*%s)" % (str(self.lhs), str(self.rhs)) class Sub: def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return "(%s-%s)" % (str(self.lhs), str(self.rhs)) def parse_expr(s, i): if s[i] not in NUMBERS: return j = i while j < len(s) and s[j] in NUMBERS: j += 1 lhs = Number(s[i:j]) if j == len(s) or s[j] not in OPERATORS: return (j + 1, lhs) op = s[j] r = parse_expr(s, j + 1) if r is None: return (i, rhs) = r if op == "-": return (i, Sub(lhs, rhs)) else: assert op == "*" return (i, Mul(lhs, rhs)) def parse(s): r = parse_expr(s, 0) if r is None or r[0] <= len(s): return "Syntax error" return r[1] print(parse("2-3*4")) print(parse("2*3-4")) print(parse("2-3-4")) print(parse("2-3")) print(parse("2")) print(parse("2--3"))