How to detect line break in Python input?

2

I need to read test cases in the following format:

3 1 2 3
4 52 2 1 87
10 51 32 1 36 21 34 32 12 34 45
200 (... 200 numeros separados por espaço)

and so on, where the first number indicates the number of numbers to come later. Each line is a test case, so I would like to read each one up to the line break, how can I do this?

I know the line break is indicated by a '\ n', but how can I go through this input string per line?

Edit: I think I was able to resolve with

import sys
while line:
    line = sys.stdin.readline()
    [operacoes em cada linha]
    
asked by anonymous 29.09.2018 / 19:05

1 answer

2

Yes - the special file sys.stdin can be read as if it were a common file - having .readline() will read a single line of it, as if it were used in a for, with something like:

for linha in sys.stdin:  the body of for will run once with each line entered.

The% builtin function input itself is equivalent, for most cases, sys.stdin.readline ( input , however, has the extra functionality of displaying an optional prompt).

In any case, in a system of this type, you can not know the end of the file. To circumvent this, many computing problems - in the model used in marathons, olimíadas or online sphere judges use this type of input, and place, in the first of all the lines a single whole number, indicating the total of lines of data.

In this case, you can do something like:

numero_de_casos = int(input())
for n_linha in range(numero_de_casos):
     linha = input()
     # e para ter todos os dados da linha, numa lista com inteiros:
     dados = [int(elemento) for elemento in linha.split()]
     # Segue código com o algoritmo que vai tratar os números
     ...
    
29.09.2018 / 20:25