Search code examples
pythonloopsmatrixcs50index-error

How do I iterate over string while iterating over the length of that string in Python


I am trying to reproduce this cost matrix:

cost matrix

At the moment, i am just playing with the Python code used to make the cost matrix. I am getting stuck because I want to have an elif statement that says

elif a_list[i] = b_list[i]:
    matrix[i][j] = min( matrix[i - 1][j] + 1,
                        matrix[i][j - 1] + 1,
                        matrix[i - 1][j - 1])

So without adding +1 to the last term. Problem is I get this error message 'IndexError: list index out of range'

How can I fix this. At the moment, my output is:

0 1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 2 3 4 5 6 7
3 3 3 3 4 5 6 7
4 4 4 4 4 5 6 7

and it should be

0 1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 1 2 3 4 5 6
3 3 2 2 3 4 5 6
4 4 3 3 3 4 5 6

My whole code atm is:

import numpy as np

a = 'harvard'
b = 'yale'

a_list = list(a)
b_list = list(b)

#print(a_list)
#print(b_list)


matrix = []

for i in range(len(a_list) + 1):
    matrix.append([])
for i in range(len(a_list) + 1):    
    for j in range(len(b_list) + 1):
        matrix[i].append(j)

        if i == 0:
            matrix[i][j] = j

        elif j == 0:
            matrix[i][j] = i

        #elif a_list[i] == b_list[j]:
        #    matrix[i][j] = min( matrix[i - 1][j] + 1,
        #                        matrix[i][j - 1] + 1,
        #                        matrix[i - 1][j - 1])
        else:
            matrix[i][j] = min( matrix[i - 1][j] + 1,
                                matrix[i][j - 1] + 1,
                                matrix[i - 1][j - 1] + 1)

for mat in zip(*matrix):
    print(*mat) 

Solution

  • You are over len+1 for a_list[i] will throw an IndexError

    just change theelif statement to

    elif a_list[i-1] == b_list[j-1]: