Cody Bentson
Cody Bentson

Reputation: 19

Reading In Integers in Python

So, my question is simple. I'm simply struggling with syntax here. I need to read in a set of integers, 3, 11, 2, 4, 4, 5, 6, 10, 8, -12. What I want to do with those integers is place them in a list as I'm reading them. n = n x n array in which these will be presented. so if n = 3, then i will be passed something like this 3 \n 11 2 4 \n 4 5 6 \n 10 8 -12 ( \n symbolizing a new line in input file)

n = int(raw_input().strip())
a = []
for a_i in xrange(n):
   value = int(raw_input().strip())
   a.append(value)

print(a)

I receive this error from the above code code:

value = int(raw_input().strip())
ValueError: invalid literal for int() with base 10: '11 2 4'

The actual challenge can be found here, https://www.hackerrank.com/challenges/diagonal-difference . I have already completed this in Java and C++, simply trying to do in Python now but I suck at python. If someone wants to, they don't have too, seeing the proper way to read in an entire line, say " 11 2 4 ", creating a new list out that line, and adding it to an already existing list. So then all I have to do is search said index of list[ desiredInternalList[ ] ].

Upvotes: 0

Views: 396

Answers (2)

mugetsu
mugetsu

Reputation: 198

You get this error because you try to give all inputs in one line. To handle this issue you may use this code

n = int(raw_input().strip())
a = []
while len(a)< n*n:
  x=raw_input().strip()
  x = map(int,x.split())
  a.extend(x)

print(a)

Upvotes: 0

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85482

You can split the string at white space and convert the entries into integers.

This gives you one list:

for a_i in xrange(n):
    a.extend([int(x) for x in raw_input().split()])

and this a list of lists:

for a_i in xrange(n):
    a.append([int(x) for x in raw_input().split()]):

Upvotes: 1

Related Questions