CODE-0006 · grok-4.5 (medium)def eval_expr(s):
def tokenize(text):
tokens = []
i = 0
n = len(text)
while i < n:
c = text[i]
if c.isspace():
i += 1
continue
if c in '+-*/()':
tokens.append(c)
i += 1
continue
if c.isdigit() or c == '.':
start = i
has_dot = False
while i < n and (text[i].isdigit() or text[i] == '.'):
if text[i] == '.':
if has_dot:
raise ValueError("malformed number")
has_dot = True
i += 1
num_str = text[start:i]
if num_str == '.' or num_str.count('.') > 1:
raise ValueError("malformed number")
if has_dot:
tokens.append(float(num_str))
else:
tokens.append(int(num_str))
continue
raise ValueError("unknown token")
return tokens
tokens = tokenize(s)
pos = 0
def peek():
if pos < len(tokens):
return tokens[pos]
return None
def consume():
nonlocal pos
if pos >= len(tokens):
raise ValueError("unexpected end")
t = tokens[pos]
pos += 1
return t
def expect(tok):
t = consume()
if t != tok:
raise ValueError("expected " + str(tok))
return t
def to_num(x):
if isinstance(x, float) and x == int(x) and abs(x) < 2**53:
return int(x)
if isinstance(x, float):
return x
return x
def apply_bin(op, a, b):
if op == '+':
r = a + b
elif op == '-':
r = a - b
elif op == '*':
r = a * b
elif op == '/':
if b == 0:
raise ValueError("division by zero")
r = a / b
else:
raise ValueError("unknown operator")
if isinstance(r, float) and r.is_integer() and abs(r) < 2**53:
return int(r)
return r
def parse_expr():
left = parse_term()
while peek() in ('+', '-'):
op = consume()
right = parse_term()
left = apply_bin(op, left, right)
return left
def parse_term():
left = parse_unary()
while peek() in ('*', '/'):
op = consume()
right = parse_unary()
left = apply_bin(op, left, right)
return left
def parse_unary():
if peek() in ('+', '-'):
op = consume()
val = parse_unary()
if op == '-':
val = -val
return to_num(val) if isinstance(val, float) else val
return parse_primary()
def parse_primary():
t = peek()
if t is None:
raise ValueError("unexpected end")
if isinstance(t, (int, float)):
return consume()
if t == '(':
consume()
val = parse_expr()
if peek() != ')':
raise ValueError("mismatched parentheses")
consume()
return val
raise ValueError("malformed expression")
if not tokens:
raise ValueError("empty expression")
result = parse_expr()
if pos != len(tokens):
raise ValueError("malformed expression")
if isinstance(result, float) and result.is_integer() and abs(result) < 2**53:
return int(result)
return result