Back to General discussions forum
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()
...
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.
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 :)
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
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.