Issue
I have been doing exercises on codeabbey.com to brush the rust off, and I keep running into this small, but still frustrating problem. I want my programs to spit out one line of n items of output and then a newline for any n lines of given input, but my programs all spit out one line of (n-1) items, a newline, and then the last item.
Here is an example in which I am given first a number of pairs to be processed, then the pairs themselves, and I am tasked with finding the minimum (Please forgive my lazy use of pre-existing functions):
quanta = int(raw_input())
print "\n"
for i in xrange(quanta):
a = raw_input().split()
a = map(int, a)
print min(a),
and this input copy-pasted into the command line:
3
5 3
2 8
100 15
I expect this output:
3 2 15
but instead I am getting this output:
3 2
15
My question then is how do I get rid of that trailing newline?
Solution
I was able to reproduce. With this in the copy buffer:
3
5 3
2 8
100 15
when running the script and pasting this without trailing newline the script stays at a = raw_input().split()
of the third input line, but already outputted the min
of the two lines above (3
and 2
), so when you hit newline then raw_input
enters the newline and the last min
(15
) is printed.
One solution is to only print at the end:
quanta = int(raw_input())
print "\n"
res = []
for i in xrange(quanta):
a = raw_input().split()
a = map(int, a)
res.append(min(a))
print(" ".join(str(i) for i in res))
The other is to also include the trailing newline in the copy-buffer (on MacOs
you need to drag down the mouse a bit under the line to get the trailing newline selected)
Answered By - hansaplast
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.