I'm working on the 'more comfortable' version of Similarities in PSET6. When I execute ./score wordone wordtwo, the IDE responds: 'Could not read wordone'. I initially thought the issue was my web server because I kept on getting errors instead of /score when I submitted via the web-app. I think the issue is with distances() function in helpers.py. Here's the code:

def distances(a, b): """Calculate edit distance from a to b""" newA = " " + a newB = " " + b rowsA = len(a) colsB = len(b)

#1 Set Up List
matrix = [None] * rowsA
for row in range(rowsA):
    matrix[row] = [None] * colsB

#2 Base Case Insertion
for row in range(rowsA):
    matrix[row][0] = (row, Operation.DELETED)

for col in range(colsB):
    matrix[0][col] = (col, Operation.INSERTED)

matrix[0][0] = (0, None)

#3 Recursive Table Creation
for row in range(rowsA):
    for col in range(colsB):
        if matrix[row][col] == None:
            deletionCost = int(matrix[row - 1][col][0]) + 1
            insertionCost = int(matrix[row][col - 1][0]) + 1
            if newA[row] == newB[col]:
                subCost = int(matrix[row - 1][col - 1][0])
                subCost = int(matrix[row - 1][col - 1][0]) + 1

            chosen = min(deletionCost, insertionCost, subCost)
            if chosen == deletionCost:
                matrix[row][col] = (deletionCost, Operation.DELETED)
            elif chosen == insertionCost:
                matrix[row][col] = (insertionCost, Operation.INSERTED)
            elif chosen == subCost:
                matrix[row][col] = (subCost, Operation.SUBSTITUTED)

return matrix

1 Answer 1


Your matrix needs to have len(a) + 1 rows of len(b) + 1 cells. The final distance is found in matrix[len(a)][len(b)], which does not exist in your current matrix. A cell matrix[row][col] corresponds to the transformation from a[0:row] into b[0:col], upper left cell matrix[0][0] would be empty string "" to "", lower right cell matrix[len(a)][len(b)] would represent transformation a to b.

That was the part that to me looks breaking, now for some thoughts reducing code, probably biased as I am:

The if matrix[row][col] == None: is a workaround you don't need if you do it right. Consider two-argument range, the one with the starting value. range by default starts at 0, but you can specify another value.

Additionally, the setup of the matrix can be done in a list comprehension, which is less code:

matrix = [[None] * colsB for i in range(rowsA)]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .