How to detect line breaking in Python input?

Asked

Viewed 684 times

2

I need to read test cases of 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 amount of numbers that will come after. Each line is a test case, so I’d like to read each one up to the line break, how can I do that?

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 figured it out with

import sys
while line:
    line = sys.stdin.readline()
    [operacoes em cada linha]
  • 1

    3 1 2 3
4 52 2 1 87
10 51 32 1 36 21 34 32 12 34 45 is a single string?

  • yes, it’s like you typed in the input, but there’s a line break at the end of each line

  • I think I figured it out, I’ll edit the question

2 answers

2


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

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

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

In any case, in such a system, there is no way of knowing the final of the archive. To overcome 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 lines a single integer, indicating the total of data lines.

In that 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
     ...

1

You can passar each of the values as elements of a given lista. In this case you can use the following algorithm...

valores = list(map(int, input('Digite os valores: ').split()))
print(valores)

See how the algorithm works on repl it..

For you to use corretamente this algorithm, must:

  1. Run the algorithm;
  2. Type all values in the same line separated by a space;
  3. Press the button Enter.

Note that this algorithm captures a number indefinido values. That is, if you type 3 values, the list valores will consist of três values. If you type 1000 values, the list valores will consist of mil values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.