2015-02-05 80 views
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失败的适当测试是什么?

+2

你为什么不试试代码并找出它是否有效? – MattDMo 2015-02-05 20:50:19

+0

是的,这是必要的,因为在没有这个循环的情况下没有输入之间的比较......有更好的方法来完成整个事情,但该循环当前是必需的。 – Ben 2015-02-05 20:51:54

+0

@MattDMo我做了,它通过了测试'anagramSolution4('abc','cba')'和'anagramSolution4('abc','cbd')'和'anagramSolution4('abc','cbah')' – Jack 2015-02-05 20:53:57

回答

2

在两个列表上使用==会产生相同的结果,但也会隐藏一些实现细节。鉴于脚本来自用于学习的网站,我想这是用于学习的目的。

此外,我看到在网页中,您会被问到一些关于复杂性的问题。那么,使用c1 == c2而不是循环可能会误导一些人,让他们认为操作是O(1)而不是O(min(len(c1),len(c2)))[1]

最后,请注意,有许多语言没有列表的概念。


[1]这不一定是真实的或者,当两个列表可以包含定制的和复杂的__eq__()方法的项目。