Python中的这个列表比较是没有必要的吗?

2024-10-01 02:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

interactivepython.org中提供的Count and Compare Anagram solution检查在列表中进行最后一次迭代,检查每个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失败?你知道吗


Tags: andposfalsetruereturnreturnsabcc2
1条回答
网友
1楼 · 发布于 2024-10-01 02:19:12

对两个列表使用==将产生相同的结果,但也会隐藏一些实现细节。鉴于脚本来自一个用于学习的网站,我猜这是为了学习的目的。你知道吗

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

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


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

相关问题 更多 >