Count and Compare Anagram solution提供于interactivepython.org检查迭代列表最后一次检查每个 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 失败的适当测试是什么?
最佳答案
在两个列表上使用 ==
将产生相同的结果,但也会隐藏一些实现细节。鉴于该脚本来自一个用于学习的网站,我猜这是为了学习目的。
此外,我发现在网页中您被问到一些有关复杂性的问题。好吧,使用 c1 == c2
而不是循环可能会误导一些人,让他们认为操作是 O(1) 而不是 O(min(len(c1), len(c2) ))[1].
最后,请注意,有许多语言没有列表的概念。
<小时/>[1] 这也不一定是真的,因为这两个列表可能包含具有自定义和复杂 __eq__()
方法的项目。
关于python - Python 中的列表比较是不必要的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28353707/