Home > Blockchain >  How to check if an element's values or it's value neighbors (within a set range) exist a l
How to check if an element's values or it's value neighbors (within a set range) exist a l

Time:11-24

I have a data variable, contains, many [x,y] coordinates:

data = ([100,200],[250,110],[50,400]...)

When I receive a new [x,y], I append it to data:

data.append ([x_cor, y_cor])

BUT

I need to filter "neighbors" coordinates (to avoid appending them), whithin the a custom set "range".

For example, if I set the range to 2, then I need to filter all coordinates where either x or y coordinate is the same, or less/more with 1 or 2 round value, like e.g.:

101,200

100,199

248,111

50,400

and so on...

When the range is only 1, I can do it using an IF and a boolean by adding all variations, like this:

cord_exist = False 

if ([x_cor   1, y_cor   1]) in data: cord_exist = True
if ([x_cor - 1, y_cor - 1]) in data: cord_exist = True
if ([x_cor   1, y_cor]) in data: cord_exist = True
if ([x_cor, y_cor   1]) in data: cord_exist = True
if ([x_cor - 1, y_cor]) in data: cord_exist = True
if ([x_cor, y_cor - 1]) in data: cord_exist = True
if ([x_cor   1, y_cor - 1]) in data: cord_exist = True
if ([x_cor - 1, y_cor   1]) in data: cord_exist = True

if cord_exist == False: data.append ([x_cor, y_cor])

This is impossible to maintain if range is 2,3 or more.

How could I solve this in a way where the range can be set freely?

CodePudding user response:

You can try this:

data = [[100,200],[250,110],[50,400]]
new = [103, 403]

margin = 2
if all(abs(d[0] - new[0]) > margin or abs(d[1] - new[1]) > margin for d in data):
    data.append(new)

CodePudding user response:

you can use range to get all 'neighbours' x coordinates and similarly all 'neighbours' y coordinates and combine them together into all neighbours point coordinates using itertools.product. Then you check for any existing point in data matches your neighbours

Example code:

from itertools import product

x_margin, y_margin = 2, 3
x_range = range(x_cor-x_margin, x_cor x_margin 1)
y_range = range(y_cor-y_margin, y_cor y_margin 1)
neighbours = set(product(x_range, y_range))
cord_exist = any(cor in neighbours for cor in data)
  • Related