关键错误:在Python中,编辑距离为0

时间:2018-12-23 03:23:18

标签: python keyerror

有人可以让我知道为什么我在以下代码的第23行看到“ Key Error:0”消息的原因吗?我正在尝试实现一个编辑距离功能,返回费用和最后的操作。谢谢!

from enum import Enum


class Operation(Enum):
    """Operations"""

    DELETED = 1
    INSERTED = 2
    SUBSTITUTED = 3

    def __str__(self):
        return str(self.name.lower())


def distances(a, b):
    """Calculate edit distance from a to b"""

    # edit distance
    x = len(a) + 1
    y = len(b) + 1
    cost = {}
    for i in range(0, x):
        cost[i][0] = i
    for j in range(0, y):
        cost[0][j] = j
    for i in range(1, x):
        for j in range(1, y):
            if a[i] == b[j]:
                sub_cost = 0
            else:
                sub_cost = 1
            cost[i][j] = min(cost[i - 1][j] + 1, cost[i][j - 1] + 1, cost[i - 1][j - 1] + sub_cost)

            # final operation
            if cost[i - 1][j] + 1 == min(cost[i - 1][j] + 1, cost[i][j - 1] + 1, cost[i - 1][j - 1] + sub_cost):
                last_operation = Operation.DELETED
            if cost[i][j - 1] + 1 == min(cost[i - 1][j] + 1, cost[i][j - 1] + 1, cost[i - 1][j - 1] + sub_cost):
                last_operation = Operation.INSERTED
            else:
                last_operation = Operation.SUBSTITUTED


    return cost[x][y], last_operation

1 个答案:

答案 0 :(得分:1)

问题在于,当您在空字典上运行cost[i][0] = i时,您试图将一个值分配给 sub -字典,但是由于您尚未初始化字典中的任何值但是,没有任何可访问的内容,因此是“关键错误”。您必须先初始化子词典,然后才能向其添加键/值

for i in range(0, x):
    cost[i] = {}
    cost[i][0] = i

或者您可以使用defaultdict来设置字典中子项目的默认值。