简体   繁体   中英

The difference between two sets of tuples

I'm trying to write a function that takes a tuple (representing an integer coordinate in the plane) and returns all adjacent coordinates not including the original coordinate .

def get_adj_coord(coord):
    '''
    coord: tuple of int

    should return set of tuples representing coordinates adjacent
    to the original coord (not including the original)
    '''

    x,y = coord

    range1 = range(x-1, x+2)
    range2 = range(y-1, y+2)

    coords = {(x,y) for x in range1 for y in range2} - set(coord)

    return coords

The issue is that the return value of this function always includes the original coordinate:

In [9]: get_adj_coord((0,0))
Out[9]: {(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)}

I'm probably missing something fundamental to sets and/or tuples, but the following function is definitely not returning what I expect. I also tried also using:

coords = {(x,y) for x in range1 for y in range2}.remove(coord)

But then function returns nothing. Can anyone point out what I'm very clearly missing here?

That's because you're not subtracting the right set object. Your current approach uses set((0,0)) -> {0} which casts the tuple into a set. However, what you want is a tuple in a set:

coords = {(x,y) for x in range1 for y in range2} - {coord}

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