Python question

Back to General discussions forum

trodrigueza     2022-01-22 20:13:48

Hi, I was doing a problem which didn't specify the number of test cases so I had to count the lines of the input data to write in my program something like:

for i in range(# of lines in input data):
    data = input()
    ...

Is there a way in which I don't have to count the number of lines manually? Idk, something like:

while there's input data:
    data = input()
    ...
rafael.adorna     2022-01-22 20:39:23
User avatar

Hi tom lite, You could pass the input as a list and then loop through it up to the number of tests cases, for example. Pretty sure there are more efficient ways than just inputting them from the console.

Rodion (admin)     2022-01-22 22:05:26
User avatar

Hi Friend!

I'm not a python guru, but this is possible in almost any language. There is a kind of end-of-input condition, so there is always a way to read "until end".

You'd better google words like "read all lines from input in python", but I vaguely remember one of recipes is like this:

import sys
userInput = sys.stdin.readlines()

# now userInput is list of strings, e.g.
print(len(userInput))

so I had to count the lines of the input data

If I'm allowed to give a general advice :) if something looks clumsy / stupid / weird in programming - google around for a bit - there should be better way :)

zelevin     2022-01-26 19:11:37

Tom:

Yes, you can do this.

from sys import stdin

for line in stdin:
    print(line, end = '')

Then you can pipe a file as input:

python test.py < test.txt
nicolas_patrois     2022-06-06 11:25:57
User avatar

I use the with keyword like this:

with open("ca-smthg.txt","r") as f:
  for i,l in enumerate(f):
    do_something

Where ca-smthg.txt contains the data. Thus, I can decide if a line contains pure data or meta data.

Please login and solve 5 problems to be able to post at forum