Valid sensor average
A sensor sends whitespace-separated tokens. Keep only tokens that are base-10 integers from 0 through 50 inclusive. Print their arithmetic mean to one decimal place and the number of rejected tokens. If none is valid, print NONE instead of a mean. Reject floats and words rather than silently coercing them.
Input
One line of whitespace-separated tokens.
Output
First line: mean to one decimal place or NONE; second line: rejected X.
Example 1
Input
10 bad 20 51 -1 0
Output
10.0 rejected 3
Ten, twenty and zero are valid, giving mean 10.0; bad, 51 and -1 each count as one rejection.
Constraints
- Each input token is considered independently.
- Only base-10 integer values from 0 through 50 are valid.
Hints
Hint 1 of 2
Catch ValueError for tokens that are not integers.
Hint 2 of 2
Check the range after parsing and avoid division when the valid list is empty.
Solution
Show a reference solution and explanation
good = []
rejected = 0
for token in input().split():
try:
value = int(token)
except ValueError:
rejected += 1
continue
if 0 <= value <= 50:
good.append(value)
else:
rejected += 1
print(f'{sum(good) / len(good):.1f}' if good else 'NONE')
print('rejected', rejected)
Why it works
Conversion and range validation are separate: a token can be a valid integer but an invalid reading. Catch only expected parse failures, count every rejection, and divide only when at least one valid value exists. The fixed one-decimal format makes the report stable.
Lesson for this exercise: Exceptions and Error Handling in Python