Reputation: 103
I am a Python beginner and started my journey by solving some Code Forces problems.
I faced some problems when trying to write Python codes for this question: https://codeforces.com/problemset/problem/339/A
Basically, the input row contains a string with numbers and '+', e.g. '3 + 2 + 1', and the codes must convert the string into a series in ascending order and print as output, e.g. output '1 + 2 + 3' from '3 + 2 + 1'.
This is my attempt:
lines = (sys.stdin.readlines())
answer = ''
arranged = []
intermediate = str((lines)[0]).split('+')
arranged += [intermediate[0]]
k = 1
i = 0
for k in range(1, len(intermediate)):
while i < len(arranged) and intermediate[k] > arranged[i]:
i += 1
arranged[i:i] = [intermediate[k]]
for item in arranged:
answer += item + '+'
print(answer[:-1])
When I ran the codes using custom test, it works: giving out '1 + 2 + 3' as output.
However, when I submitted my answer, the output was given as
1
+ 2 + 3
making my codes fail in first test.
Attached image to show what I meant:
What's wrong?
Upvotes: 0
Views: 137
Reputation: 391
The problem is that readlines()
captures a blank line (\n) that is attached to '1'.
Consider this solution, using 'strip' to remove the unwanted \n:
intermediate = str((lines)[0]).strip().split('+')
In this case a debug print would have been really useful. By printing 'intermediate', the result is:
['3', '2', '1\n']
And you could have easily detected your problem.
Upvotes: 1
Reputation: 8064
I think readlines()
captures a newline character \n
that's "attached" to the 1
when you do the split
. You can use the strip function to remote leading and trailing whitespace characters.
Upvotes: 1