0

Input:
691 41
947 779

Output:
1300
336

I have tried this solution a link

but my problem is end of last line is unknown

My Code:

for line in iter(input,"\n"):                                                               
    a,b = line.split()
    a = int(a)
    b = int(b)
    result = 2 * (a - b)
    print(result)

My code is printing the desired output but the for loop is not terminating. I am a new bee to python is there any way to find the last input from the stdin console???

DRV
  • 676
  • 1
  • 8
  • 22

4 Answers4

2

Function input is stripping trailing \n, so just use empty string as delimiter in function iter.

gcx11
  • 128
  • 4
  • i have tried with empty string as delimiter but in that case also for loop is not terminating. – DRV Feb 27 '17 at 08:55
2

What are you missing is that input() strips the newline from the end of the string it returns, so that when you hit <RET> all alone on a line what iter() sees (i.e., what it tests to eventually terminate the loop) is not "\n" but rather the empty string "" (NB definitely no spaces between the double quotes).

Here I cut&paste an example session that shows you how to define the correct sentinel string (the null string)

In [7]: for line in iter(input, ""):
   ...:     print(line)
   ...:     
asde
asde


In [8]: 

As you can see, when I press <RET> all alone on a n input line, the loop is terminated.

ps: I have seen that gcx11 has posted an equivalent answer (that I've upvoted). I hope that my answer adds a bit of context and shows how it's effectively the right answer.

Community
  • 1
  • 1
gboffi
  • 22,939
  • 8
  • 54
  • 85
0

you mentioned that you tried this But it seems that you implement a '\n' as sentinel (to use a term from the post from the link).

You may need to try to actually use a stop word, something like this:

stopword = 'stop'
for line in iter(input, stopword):                                                               
    a,b = line.split()
    a = int(a)
    b = int(b)
    result = 2 * (a - b)
    print(result)
Community
  • 1
  • 1
Edwin van Mierlo
  • 2,398
  • 1
  • 10
  • 19
0

Probably not what you need, but I didn't figure out where your inputs comes from, I tried to adapt your code by reading everything from std in using fileinput and leaving when "Enter" is pressed:

import fileinput

for line in fileinput.input():
    if line == '\n':
        break
    a, b = line.split()
    a = int(a)
    b = int(b)
    result = 2 * (a - b)
    print(result)
Kruupös
  • 5,097
  • 3
  • 27
  • 43
  • I didn't know the built-in function `input`. My sricpt works if you use it outside of the python `console` otherwise @gboffi answers is probably what you are looking for. – Kruupös Feb 27 '17 at 09:48