Reputation: 831
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?
Upvotes: 0
Views: 126
Reputation: 78556
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}
Upvotes: 4