Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的列表比较是否不必要?_Python_List_List Comparison - Fatal编程技术网

Python中的列表比较是否不必要?

Python中的列表比较是否不必要?,python,list,list-comparison,Python,List,List Comparison,提供的at检查在列表中进行迭代,以便最后检查每个ASCII值的计数是否相同 j = 0 stillOK = True while j<26 and stillOK: if c1[j]==c2[j]: j = j + 1 else: stillOK = False return stillOK 完整代码: def anagramSolution4(s1,s2): c1 = [0]*26 c2 = [0]*26 fo

提供的at检查在列表中进行迭代,以便最后检查每个ASCII值的计数是否相同

j = 0
stillOK = True
while j<26 and stillOK:
    if c1[j]==c2[j]:
        j = j + 1
    else:
        stillOK = False

return stillOK
完整代码:

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'))

…他们都通过了。显示c1==c2失败的适当测试是什么?

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

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

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



[1] 这也不一定是真的,因为这两个列表可能包含具有自定义和复杂
\uuuu eq\uuuu()
方法的项。

为什么不试试代码,看看它是否有效?是的,这是必要的,因为在没有此循环的情况下,无法对输入进行比较。。。有更好的方法来完成整个过程,但这个循环目前是必要的。@MattDMo我做到了,它通过了测试
anagramSolution4('abc','cba')
anagramSolution4('abc','cbd')
anagramSolution4('abc','cbah'))
这并不能回答您的问题,但有一种更简单的方法可以使用
collections.Counter
、生成器表达式和字符串方法来实现这一点。首先创建一个辅助函数
def letter_counts(s):返回计数器(如果c.isalpha(),则返回c.lower())
,然后比较
letter_counts(s1)=letter_counts(s2)
。如果只比较没有标点或空格的小写单词,则可以省略helper函数:
Counter(s1)==Counter(s2)
。同样,解决方案2也可以重新实现为
sorted(s1)==sorted(s2)
。我怀疑这段冗长的代码的目的是让初学者明白所有的步骤。
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