rgkbitw's blog

By rgkbitw, history, 4 years ago, In English

I came across this problem in UVa OJ. 272-Text Quotes

Well, the problem is quite trivial. But the thing is I am not able to read the input. The input is provided in the form of text lines and end of input is indicated by EOF.

In C/C++ this can be done by running a while loop:

  while( scanf("%s",&s)!=EOF ) { //do something } 

How can this be done in python .?
I have searched the web but I did not find any satisfactory answer.

Please Help Me!
 
 
 
 
  • Vote: I like it
  • +5
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

in python 3:

while True:
    try:
        s=input()
        #do something
    except EOFERROR:
        break
  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Using exception handling is expensive and might cause an overhead. Is there any simpler way?

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      I always use it whenever i submit in UVA IN PYTHON. However you can take a look here..but I think you did..

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Yes! I did.
        I used sys module.

           import sys;  inp=sys.stdin.read()  

        It's documentation says:
          read(size=-1, /) method of _io.TextIOWrapper instance  Read at most n characters from stream.
        
        Read from underlying buffer until we have n characters or we hit EOF.
         If n is negative or omitted, read until EOF.

        Then iterate over this inp.
        As KarlisS has mentioned already!
»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

Just iterate over the input.

for line in sys.stdin:
    process_line(line)
  • »
    »
    2 years ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    I am not able to take break out of loop using this.

    Here is the input

    aasdad

    asdfadsfds

    fdasfsf

    Now I want to take them as input. Here is what I tried for S in input().split('\n') but it takes only 1st input. Please help me :)

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

That's why you don't do UVa (if possible) :P.