def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)
此方法是从python代码中复制的,该代码用于在输入时预测单词。我想知道为什么在R for c in letters
中使用'R'很重要。
答案 0 :(得分:2)
变量splits
如下所示:
[('', 'word'), ('w', 'ord'), ('wo', 'rd'), ('wor', 'd'), ('word', '')]
后续分配使用L
(左)和R
(右)来引用此列表中的每对元素。因此,对于第二个元素,L == 'w'
和R == 'ord'
。
如果我们采用L
和R
的值,则此行:
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
给出'w' + 'r' + 'o' + 'd'
,换句话说,它交换R
的前两个字母,以使'ord'
变成'rod'
。