Speed differences between intersection() and 'object for object in set if object in other_set'

后端 未结 4 1241
谎友^
谎友^ 2021-02-09 10:02

Which one of these is faster? Is one \"better\"? Basically I\'ll have two sets and I want to eventually get one match from between the two lists. So really I suppose th

4条回答
  •  猫巷女王i
    2021-02-09 10:48

    I wrote a simple utility that checks if two sets have at least one element in common. I had the same optimization problem today and your post saved my day. This is just a way to thank you for pointing this out, hope this will help other people too :)

    Notice. The utility does NOT return the first element in common but rather returns true if they have at least one element in common, false otherwise. Of course it can be easily hacked to meet your goal.

    def nonEmptyIntersection(A, B):
        """
        Returns true if set A intersects set B.
        """
        smaller, bigger = A, B
        if len(B) < len(A):
            smaller, bigger = bigger, smaller
        for e in smaller:
            if e in bigger:
                return True
        return False
    

提交回复
热议问题