Stop At First Bad Number
Python
Medium
2 views
Problem Description
Read a list of tokens ending with END. Start sum=0. Add each token as integer. If a token is not integer (and not END), output BAD and stop. If all good, output sum.
Input Format
One line tokens ending with END.
Output Format
BAD token or sum.
Constraints
Up to 200000 tokens.
Official Solution
import sys
p=sys.stdin.read().strip().split()
sm=0
for t in p:
if t=='END':
sys.stdout.write(str(sm))
raise SystemExit
try:
sm+=int(t)
except Exception:
sys.stdout.write('BAD '+t)
raise SystemExit
sys.stdout.write(str(sm))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!