1

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 失败的适当测试是什么?

4

1 回答 1

2

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

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

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


[1]这也不一定正确,因为这两个列表可能包含具有自定义和复杂__eq__()方法的项目。

于 2015-02-05T21:06:02.980 回答