Reputation: 23
Can anyone point me to what's wrong?
I got stuck on newGrid.setValue(n[k][0], n[k][1], List[k])
trying to feed the values of each x/y of each coord into a different function, which takes three arguments, x y and value. Value is what is printed in a position on a grid, x & y are the coordinates.
self.listOfRows[x - 1][y - 1] = value
IndexError: list assignment index out of range
def gridMileage(List):
x = []
y = []
n = []
k = 0
best = 0
while len(List) > 0:
for i in range(len(List)):
x = List[i][0]
y = List[i][1]
n.append([x,y])
if x > best:
best = x
elif y > best:
best = y
newGrid = Grid(best)
while k < 2:
newGrid.setValue(n[k][0], n[k][1], List[k])
k = k + 1
del List[0]
del List[1]
del n[0]
del n[1]
newGrid.setValue(n[0], n[0] + 1, math.sqrt((n[0][0] - n[1][0])**2 + (n[0][1] - n[1][1])**2))
newGrid.setValue(n[1] + 1, n[1], math.sqrt((n[1][0] - n[0][0])**2 + (n[1][1] - n[0][1])**2))
z = len(newGrid.listOfRows)
while z > 0:
print(newGrid.listOfRows[z - 1])
z = z - 1
class Grid:
def __init__(self, n):
self.listOfRows = []
for i in range(n):
row = []
for j in range(n):
row.append('*')
self.listOfRows.append(row)
def setValue (self, x, y, value):
self.listOfRows[x - 1][y - 1] = value
Upvotes: 2
Views: 11684
Reputation: 1
self.listOfRows[x - 1][y - 1] = value
what if x
and y
are 0
that gives you
self.listOfRows[-1][-1] = value
it doesnt exist
Upvotes: 0
Reputation: 64338
The problem is that ultimately, you appear to be feeding in a list index that is either too small, or too large.
According to the error message, the problematic piece of code is self.listOfRows[x - 1][y - 1] = value
. You call it by doing newGrid.setValue(n[k][0], n[k][1], List[k])
. The problem can't be List[k]
, since that's not what's causing the stacktrace.
Therefore, that means either n[k][0]
or n[k][1]
is too big for newGrid.listOfRows
.
I would double-check your code by adding in print statements before that line to examine those two values, as well as double-checking exactly how large your grid is.
Since the only place you appear to add any values to n
is at (I think?):
for i in range(len(List)):
x = List[i][0]
y = List[i][1]
n.append([x,y])
...that implies that the root issue is ultimately with the List
variable that you've passed in.
Upvotes: 2