Matt
Matt

Reputation: 13

Python building 2d array getting list assignment index out of range

N = len(s1)
M = len(s2)
matrix = [[0 for i in range(N+1)] for j in range(M+1)]
gap = int(raw_input('Enter gap score'))
mismatch = int(raw_input('Enter mismatch score'))
match = int(raw_input('Enter the match score'))

matrix[0][0] = 0

for i in range(1,(N+1)):
    matrix[i][0]=(matrix[(i-1)][0] + gap)

for j in range(1,(M+1)):
    matrix[0][j]=(matrix[0][(j-1)] + gap)  

for i in range(1,N+1):
    for j in range(1,M+1):
        if(s1[i-1] == s2[j-1]):
            score1 = matrix[i-1][j-1] + match

        else:
            score1 = matrix[i-1][j-1] + mismatch

        score2 = matrix[i][j-1] + gap
        score3 = matrix[i-1][j] + gap
        matrix[i][j] = max(score1, score2, score3)

I get the error code Traceback (most recent call last): File "C:\Users\Matt\workspace\ch3skills\ch3skills.py", line 67, in matrix[0][j]=(matrix[0][(j-1)] + gap)
IndexError: list assignment index out of range

Upvotes: 0

Views: 2449

Answers (2)

Arundas R
Arundas R

Reputation: 770

The error is with defining the matrix. If N and M are same you will not get an error. With different N and M values you find the error. Consider the case for N=1 and M=2 your matrix is [[0, 0], [0, 0], [0, 0]]. Now consider this bit of code: for i in range(1,(M+1)): matrix[i][0]=(matrix[(i-1)][0] + gap) In case you have i with values 1 to 3, but you don't have matrix[3][0]. This gives such an error. I cannot understand what is code is intended to do. Now changing M and N i don't get any further errors. But i am not sure whether you are looking for this. I will include the code also.

s1 = raw_input('1: ')
s2 = raw_input('2: ')
N = len(s1)
M = len(s2)
matrix = [[0 for i in range(N+1)] for j in range(M+1)]
gap = int(raw_input('Enter gap score'))
mismatch = int(raw_input('Enter mismatch score'))
match = int(raw_input('Enter the match score'))

matrix[0][0] = 0

for i in range(1,(M+1)):
    matrix[i][0]=(matrix[(i-1)][0] + gap)

for j in range(1,(N+1)):
    matrix[0][j]=(matrix[0][(j-1)] + gap)  

for i in range(1,M+1):
    for j in range(1,N+1):
        if(s1[j-1] == s2[i-1]):
            score1 = matrix[i-1][j-1] + match

        else:
            score1 = matrix[i-1][j-1] + mismatch

        score2 = matrix[i][j-1] + gap
        score3 = matrix[i-1][j] + gap
        matrix[i][j] = max(score1, score2, score3)

Upvotes: 1

tom10
tom10

Reputation: 69242

You need to switch M and N in your for loops, like this:

for i in range(1,M+1):
    matrix[i][0] = matrix[i-1][0] + gap

for j in range(1,N+1):
    matrix[0][j] = matrix[0][j-1] + gap  

Since you initially make M items, each being a list of length N, matrix[x] is the xth list (of length N).

Also: 1) all those parentheses add too much clutter; 2) numpy would make all of this much easier.

Upvotes: 0

Related Questions