interactivepython.org提供的Count and Compare Anagram 解决方案检查迭代列表,最后检查每个 ASCII 值的计数是否相同。
j = 0
stillOK = True
while j<26 and stillOK:
if c1[j]==c2[j]:
j = j + 1
else:
stillOK = False
return stillOK
为什么不使用比较运算符?
return (c1 == c2)
完整代码:
def anagramSolution4(s1,s2):
c1 = [0]*26
c2 = [0]*26
for i in range(len(s1)):
pos = ord(s1[i])-ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(s2)):
pos = ord(s2[i])-ord('a')
c2[pos] = c2[pos] + 1
j = 0
stillOK = True
while j<26 and stillOK:
if c1[j]==c2[j]:
j = j + 1
else:
stillOK = False
return stillOK
print(anagramSolution4('apple','pleap'))
编辑添加:
我已经测试过:
anagramSolution4('abc','cba') #returns True
anagramSolution4('abc','cbd') #returns False
anagramSolution4('abc','cbah') #returns False
..他们都通过了。显示 c1==c2 失败的适当测试是什么?