python - Python 中的列表比较是不必要的吗?

标签 python list list-comparison

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/

相关文章:

python - 有效地将一系列集成到 pandas 数据框中

python - 向后差异编码如何用于测试集?

python - 检查列表是否包含 4 个相同值的元素

excel - 比较 Excel 中的 2 个列表?

c# - 比较两个列表以在其中一个列表中查找添加或删除的元素

python - redhat openshift cloud 中的 flask 静态文件

python - 数据透视表中 Y 相对于 Y 的变化

R- Shiny | cat(list(...),file,sep,fill,labels,append)中的错误: argument 1 (type 'list' ) cannot be handled by 'cat'

asp.net-mvc - MVC 4 列表模型向 Controller 返回 null

Python 在没有 shell=false 和数组中的变量的情况下使用子进程时出错