Controller
Controller

Reputation: 529

input with delimiters in python

I have a problem with the following specification:

Input:

First line contains an integer N , the number of element in the given sequnce. Then follows N integers A1, A2.... An, Ai is ith element of the given sequence. These numbers may be either space separated or newline separated.

How can I handle an input like that? I tried the following,but it only works for space separated elements.When used with newline separated elements the grader throws "time exceeded"

import sys
counter=0
A=[]
for line in sys.stdin:
    if counter!=0:
        A+=[int(Ai) for Ai in line.split()]
    else:
        N=int(line)
        counter+=1

Upvotes: 0

Views: 2495

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 113945

Assuming that you're reading from a file (sys.stdin is also a file):

f = open('path/to/file')
N = int(f.readline().strip())
A = []
while len(A) < N:
    A.extend(int(i) for i in f.readline().strip().split())

Hope this helps

Upvotes: 1

Related Questions