I am working on the distance function in pset6 similarities (more comfortable). When I run ./score cat ate, it gives me the error "could not read cat". I copied my code to another tab to test out my code, and the answers for matrix are right. I have no clue what the problem is. Please help.

def distances(a, b):
"""Calculate edit distance from a to b"""
h = len(a) + 1
w = len(b) + 1

# set up 2D array
matrix = [[0 for x in range(w)] for y in range(h)]

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

# add value for base case
for x in range(1, h):
    matrix[x][0] = (x, Operation.DELETED)
for y in range(1, w):
    matrix[0][y] = (y, Operation.INSERTED)

# add value for other entries
for i in range(1, h):
    for j in range(1, w):
        cost_del = matrix[i-1][j][0]
        cost_ins = matrix[i][j-1][0]
        cost_sub = matrix[i-1][j-1][0]

        cost = min(cost_del, cost_ins, cost_sub)
        if cost == cost_del == cost_sub and a[i-1] != b[j-1]:
            matrix[i][j] = (cost_del + 1, Operation.DELETED)
        elif cost == cost_ins == cost_sub and a[i-1] != b[j-1]:
            matrix[i][j] = (cost_ins + 1, Operation.INSERTED)
        elif cost == cost_sub:
            if a[i-1] == b[j-1]:
                matrix[i][j] = (cost_sub, Operation.SUBSTITUTED)
                matrix[i][j] = (cost_sub + 1, Operation.SUBSTITUTED)
        elif cost == cost_del:
            matrix[i][j] = (cost_del + 1, Operation.DELETED)
            matrix[i][j] = (cost_ins +1, Operation.INSERTED)
return matrix

score expects your text in files. Are cat and ate text files?

Also, to check your operations are correct, you might have to use the flask run web thing.

Your way of picking an operation looks overly complicated. Why don't you calculate total cost (including the +1 except for "substituting" same character) before applying min?

  • Fixed it. Thank you for the good advice. Appreciate your help! – Stella. H Oct 8 '18 at 19:14

You must log in to answer this question.

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