1
interactivepython.org提供的Count and Compare Anagram solution通过列表检查迭代,以便最终检查每个ASCII值的计数是否相同。Python中的这个列表比较是否不必要?
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
..they所有通:
我已经与测试。显示c1 == c2失败的适当测试是什么?
你为什么不试试代码并找出它是否有效? – MattDMo 2015-02-05 20:50:19
是的,这是必要的,因为在没有这个循环的情况下没有输入之间的比较......有更好的方法来完成整个事情,但该循环当前是必需的。 – Ben 2015-02-05 20:51:54
@MattDMo我做了,它通过了测试'anagramSolution4('abc','cba')'和'anagramSolution4('abc','cbd')'和'anagramSolution4('abc','cbah')' – Jack 2015-02-05 20:53:57