Sum of Valid Integers
Python
Medium
2 views
Problem Description
Read n tokens. Add only those tokens that are valid integers. Output the sum (0 if none valid).
Input Format
First line n. Second line has n tokens.
Output Format
One integer sum.
Sample Test Case
Input:
7
1 two 3 -4 5x 6 7
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2:
sys.stdout.write('0')
else:
try:
n=int(lines[0].strip())
except Exception:
sys.stdout.write('0')
raise SystemExit
toks=lines[1].split()[:n]
sm=0
for t in toks:
try:
sm+=int(t)
except Exception:
pass
sys.stdout.write(str(sm))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!