简体   繁体   中英

Python-New To Python and programming in general-difference of two sets

The difference of two sets A and B, denoted 𝐴\\𝐵 or A – B is the set of elements in A that are not in B. Returns True exactly when there exists an element in A - B. I know it's not correct, but here is what i've tried

def hasNonemptyDiff(A,B):

    foundExampleYet = False

    for a in A:

        if(A in B):

            foundExampleYet = True

    return foundExampleYet

You're very close!

def hasNonemptyDiff(A,B):
    foundExampleYet = False
    for a in A:
        if(a in B): # here's the change
            foundExampleYet = True
    return foundExampleYet

What you want to do is check that, for every item, that item is in B. What you are saying is that, for every item, check if the whole list A is in B. That's not what you mean! More useful variable names than A, B, a, and b, will help avoid this problem in the future.

The set stuff is probably not the clearest way to talk about this question (you're not solving it by using Sets, are you?). It's pretty straightforward just to ask "are there any items in A not in B"

Simplest Way

A far simpler way, depending on your input, would be

return A == B

Most Fun Way

or, if you need to compare element-wise,

return all( [a==b for a,b in zip(A,B)] )

That last one uses the zip function to pair the sets, the "all" function to check if every element in the array is True, and list comprehension to compress the for-loop

The zip function https://docs.python.org/2/library/functions.html#zip

The all function https://docs.python.org/2/library/functions.html#all

List comprehension https://docs.python.org/2/tutorial/datastructures.html

Python has lots of great tools for problems like these that you'll discover as you learn!

If you are dealing with Python sets you can do this in a simpler way. Try it on a Python shell:

>>> a = {1,2,3}
>>> b = {2,3}
>>> c = a-b
>>> c
{1}

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