Command Processor With Errors
Python
Medium
3 views
Problem Description
You will receive q commands: ADD x, SUB x, MUL x. Start value=0. If any command has invalid number or unknown op, output ERROR at line i (1-based) and stop. Else output final value.
Input Format
First line q. Next q lines commands.
Output Format
Final value or error message.
Sample Test Case
Input:
4
ADD 5
MUL 2
SUB x
ADD 1
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
try:
q=int(lines[0].strip())
except Exception:
sys.stdout.write('ERROR at line 1')
raise SystemExit
val=0
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2:
sys.stdout.write(f'ERROR at line {i}')
raise SystemExit
op=parts[0]
try:
x=int(parts[1])
except Exception:
sys.stdout.write(f'ERROR at line {i}')
raise SystemExit
if op=='ADD':
val+=x
elif op=='SUB':
val-=x
elif op=='MUL':
val*=x
else:
sys.stdout.write(f'ERROR at line {i}')
raise SystemExit
sys.stdout.write(str(val))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!