While coding for competitions in codechef, I face this problem with python, to read
3 # number of required input 1 4 2 # inputs
To separate input by spaces:
data=list(map(int,input().split(' ')))
To verify wether the correct amount of numbers were passed:
if len(data) > n: # where n is your number of required input
# Raise an exception or ask for the input again.
You may use list comprehension syntax:
req_size = int(input().strip())
data = [int(i) for i in input().strip().split()[:req_size]]
explanation: .strip()
method removes \n
and oyher whitespace symbols from the start and end of the string. .split()
method splits string by any whitespace symbol. If you prefer to split only by whitespaces, use ' ' character explicitly: .split(' ')
. Split method returns list, and you can use [:req_size] to get firsr req_size
elements from it (stabdart list syntax). Then int
type applied to your data with list comprehension syntax (shorthand for the for
loop).