简体   繁体   中英

Fast way to check two lists for consistency

I need to check two lists for consistency, eg to return True if the first list dosen't contain elements, which are not present in second list, and if the count of similar elements is the same. By now, I came out with following:

def is_consistent(spec_a, spec_b):
    for a in spec_a:
        if spec_a.count(a) != spec_b.count(a):
            return False
    return True

But I need to do it in a loop, so I wonder, can it be faster?

If I'm understanding the question properly, perhaps you could use a Counter :

from collections import Counter
def is_consistent(spec_a, spec_b):
    c1 = Counter(spec_a)
    c2 = Counter(spec_b)
    result = c1 - c2
    return all(result[key] == 0 for key in c1)

The loop is unavoidable -- It will always be there in some form or another. In fact, I have 3 loops here. (one in each Counter and then the most obvious one at the end). However, the operation that my solution avoids is the .count which is another implicit loop nested inside another loop.

Nested loops are generally the ones you want to eliminate because if the outer loop iterates N times and the inner loop iterates N times than you have a total of N*N iterations. Compare that to my solution which has only ~3*N iterations (3 loops with about N iterations each). If N is big, you can see how this would lead to a large number of operations being saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM