Editor

Numbers From a Form

#547 · Errors and exceptions · Beginner · 30 XP · about 5 min

A web form sends every answer as text, and people type all sorts of things into a box that asks for a number. Write parse_numbers(entries) that turns each string in the list entries into a whole number with int(), and returns a tuple (numbers, rejected): the list of numbers that could be read, in their order, and how many entries could not be read.

int() raises a ValueError for text that is not a whole number, such as 'abc', '3.5' or an empty string. Catch that error and count the entry instead of crashing. int() accepts spaces around the digits and a sign in front, so ' 12 ', '-3' and '+4' are all fine.

Examples

parse_numbers(['12', 'abc', ' 7 ', '3.5'])  # returns ([12, 7], 2)
parse_numbers(['-3', '+4', ''])             # returns ([-3, 4], 1)

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.