本文要点在于算法的设计:如果两个单词中不相同的字母足够少,并且随机选择几个字母在两个单词中具有相同的前后顺序,则认为两个单词是等价的。
目前存在的问题:可能会有误判。
from random import sample, randint
def oneInAnother(one, another):
'''用来测试单词one中有多少字母不属于单词another'''
return sum((1 for ch in one if ch not in another))
def testPositions(one, another, positions):
'''用来测试单词one中位置positions上的字母是否
与单词another中的相同字母具有同样的前后顺序'''
#获取单词one中指定位置上的字母
lettersInOne = [one[p] for p in positions]
print(lettersInOne)
#这些字母在单词another中的位置
positionsInAnother = [another[p:].index(ch)+p for p, ch in zip(positions,lettersInOne) if ch in another[p:]]
print(positionsInAnother)
#如果这些字母在单词another中也具有相同的前后位置关系,返回True
if sorted(positionsInAnother)==positionsInAnother:
return True
return False
d