Reputation: 351
Am trying to build a matrix from scratch using Python Lists in Hackerrank.
The problem is that the code is running fine in sublime text but not in Hackerrank console.
It's showing this error.
Traceback (most recent call last):
File "Solution.py", line 8, in <module>
filter[k][j] = int(input())
ValueError: invalid literal for int() with base 10: '[[1, 0, 1], [0, 1, 0], [1, 0, 1]]'
Input
filter = []
for k in range(3):
for j in range(3):
filter[k][j] = int(input())
What could be the reason?
Is there a more efficient way in creating matrices from scratch. Any suggestions will be appreciated. Thank You!
Upvotes: 0
Views: 36
Reputation: 51643
You have 2 problems:
Hackerrank presents your input as one string:
'[[1, 0, 1], [0, 1, 0], [1, 0, 1]]'
not as sinlge integers followed by a return.
You need to take one string, then split it. Easiest way would be literal_eval
to create the full list of lists by this string input.
from ast import literal_eval
inp = "[[1, 0, 1], [0, 1, 0], [1, 0, 1]]" # use input() here
l = literal_eval(inp)
print(l)
print(type(l))
wich will print:
[[1, 0, 1], [0, 1, 0], [1, 0, 1]]
<class 'list'>
Your code can't run fine as is - it would give you an index error:
Traceback (most recent call last):
File "whatever.py", line 5, in <module>
filter[k][j] = int(input())
IndexError: list index out of range
because you try to access elements of your list that are not yet there:
filter = [] for k in range(3): for j in range(3): filter[k][j] = int(input())
filter
is an empty list, you cannot access/index into filter[0][0]
- you would need to change it to
filter = []
for k in range(3):
# add a new empty list
filter.append([])
for j in range(3):
# add stuff to the last list of filter
filter[-1].append( int(input()) )
Upvotes: 1