括号和范围中的Python变量

时间:2018-06-16 10:08:59

标签: python levenshtein-distance

这是什么意思([i] + [0] * n)为什么 i 0 在括号中?

previous, current = current, [i]+[0]*n

为什么我不能在下一行打印当前值?像这样:

previous, current = current, [i]+[0]*n
print(current)

我有一个错误: TabError:缩进中标签和空格的使用不一致

#!/usr/bin/env python

# This is a straightforward implementation of a well-known algorithm, and thus
# probably shouldn't be covered by copyright to begin with. But in case it is,
# the author (Magnus Lie Hetland) has, to the extent possible under law,
# dedicated all copyright and related and neighboring rights to this software
# to the public domain worldwide, by distributing it under the CC0 license,
# version 1.0. This software is distributed without any warranty. For more
# information, see <http://creativecommons.org/publicdomain/zero/1.0>


def levenshtein(a,b):
    "Calculates the Levenshtein distance between a and b."
    n, m = len(a), len(b)
    if n > m:
        # Make sure n <= m, to use O(min(n,m)) space
        a,b = b,a
        n,m = m,n

    current = range(n+1)
    for i in range(1,m+1):
        previous, current = current, [i]+[0]*n
        for j in range(1,n+1):
            add, delete = previous[j]+1, current[j-1]+1
            change = previous[j-1]
            if a[j-1] != b[i-1]:
                change = change + 1
            current[j] = min(add, delete, change)

    return current[n]

if __name__=="__main__":
    from sys import argv
    print(levenshtein(argv[1],argv[2]))

1 个答案:

答案 0 :(得分:1)

以下错误

  

TabError:标签和空格的使用不一致   压痕

只是意味着缩进不正确。所以,使用文本编辑器检查缩进是否正确。

来到

  

previous,current = current,[i] + [0] * n

在下面的for循环中给出了

for i in range(1,m+1):
        previous, current = current, [i]+[0]*n

所以,我是索引(或计数器变量),他正在做的是制作一个列表,其中第一个元素作为索引,后面跟着n个零。这里n是在下面的代码

中计算的第一个字符串的长度
n, m = len(a), len(b)

所以,例如,如果n = 10且i = 1,那么 [i] + [0]*n将是

[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

所以,他只是想制作如上所示的清单