frodo
frodo

Reputation: 1571

Splitting input into lines in python

I am trying to solve this problem http://www.spoj.pl/problems/PEBBMOV/. I think I have the right algorithm, that is not the point of this question. This problem has a weird input file to it. The input for one test case should be of the form n a1 a2 a3 ...an. (all ints)

The problem here is that , there are stray newline characters etc in between the a[i]s. I need to be able to skip such newlines and collect all a[i]s belonging to one test case at a place. How do I know all this? Well a string of WAs and Runtime Errors , plus some research on the forums. I have the following python code to try to do this, except that i seem to be faltering at crucial places and just cant get it done. I hope to have the appropriate input lines in the list lines[] at the end of the input reading.

Could someone please tell me my mistake(s) here.? Or suggest a better approach?. Thanks in advance..

import sys
#data = sys.stdin.readlines()
#lines = inp.split('\n')
data = sys.stdin.read()
pos = 0
lno = 0

lines = []
while pos<len(data):
    while not data[pos].isdigit():
                   pos = pos + 1
num =data[pos]
print num
cur = pos + 1
numbers_collected = 0

x = [] # temp list
y = []
while numbers_collected < num:

    if cur<len(data) and data[cur].isdigit():
        y.append(data[cur])
        cur = cur + 1
        numbers_collected += 1
    else:
        if cur<len(data)and numbers_collected < num:
            cur = cur + 1
        else:
            break
print x
pos = cur
x.extend(y)
lines.extend(x)



for line in lines:
    print line

Upvotes: 1

Views: 5057

Answers (3)

jfs
jfs

Reputation: 414079

The spoj problem says that each game has exactly one input line:

for line in sys.stdin:
    n, *piles = map(int, line.split())
    assert len(piles) == n

Let's assume that there could be newlines in between numbers in the same game:

numbers = (int(s) for line in sys.stdin for s in line.split() if line.strip())
for n in numbers:
    piles = list(itertools.islice(numbers, n))
    assert len(piles) == n

Upvotes: 0

UltraInstinct
UltraInstinct

Reputation: 44424

Something like this can help:

numbers = map(int, sys.stdin.read().split())
#numbers = [1,2,3,4,5]

This is a quick and dirty solution because it treats all whitespace as separators.

Upvotes: 0

Asim Ihsan
Asim Ihsan

Reputation: 1501

Does this help you answer your question?

In [1]: s1 = "1\n2\n\n3\n\n\n4\n\n\n\n5\n\n\n\n\n6"

In [2]: s1
Out[2]: '1\n2\n\n3\n\n\n4\n\n\n\n5\n\n\n\n\n6'

In [3]: s1.splitlines()
Out[3]: ['1', '2', '', '3', '', '', '4', '', '', '', '5', '', '', '', '', '6']

In [4]: [elem for elem in s1.splitlines() if elem]
Out[4]: ['1', '2', '3', '4', '5', '6']

Without seeing example input it's difficult to answer the question. However, the SPOJ problem page does not provide example input, so the OP can't provide something that isn't available.

Upvotes: 2

Related Questions