Find coordinates in an Array of Objects

Asked by At

I have an array of objects like this [{'x': -50, 'y': 30}, {'x': 70, 'y': -68} ...] max range is -200| +200.

I need to find all coords in a range from some coords. Let say I add coords 50|50 and range 20 so max x is 70 low 30 and max y 70 and low y 30.

So it should find all coords in that range and return a new list of objects.

I tried this and its work for x coords but not much for y.

Thanks for any help.

def find_coords(self, x, y, z):
    with open('allcoords.json') as json_file:
        data = json.load(json_file)
        xcoords = []
        for s in data:
            if s['x'] > (int(x) + int(z)):
                break
            if s['x'] > (int(x) - int(z)):
                xcoords.append(s)
        ycoords = []
        for ys in xcoords:
            if ys['y'] > (int(y) + int(z)):
                break
            if ys['y'] > (int(y) - int(z)):
                ycoords.append(ys)

1 Answers

0
losik123 On Best Solutions

You're iterating over an array of dicts, which is stored in your allcords.json. The code itself is ok, but for the Y coordinates you're referencing the wrong source data. The Y cords are also in data, but you're iterating over ycoords, which is an empty array and doesn't make any sense.

def find_coords(self, x, y, z):
    with open('allcoords.json') as json_file:
        data = json.load(json_file)
        xcoords = []
        for s in data:
            if s['x'] > (int(x) + int(z)):
                break
            if s['x'] > (int(x) - int(z)):
                xcoords.append(s)
        ycoords = []
        for ys in data:
            if ys['y'] > (int(y) + int(z)):
                break
            if ys['y'] > (int(y) - int(z)):
                ycoords.append(ys)

Also, this code is in my opinion a bit too complicated. You could rewrite is as the following with the filter method and make it more readable:

def find_coords(self, x, y, z):
    with open('allcoords.json') as json_file:
        data = json.load(json_file)
        xcoords = list(filter(lambda s:  int(x) - int(z) < s['x'] < int(x) + int(z), data))
        ycoords = list(filter(lambda s:  int(y) - int(z) < s['y'] < int(y) + int(z), data))

EDIT: Based on the discussion in the comments.

Sorry, I misinterpreted what exactly you wanted. I suppose in the end you would probably just need the following:

def find_coords(self, x, y, z):
    with open('allcoords.json') as json_file:
        data = json.load(json_file)
        coords = list(
            filter(
                lambda s: (
                   int(x) - int(z) < s['x'] < int(x) + int(z)
                   and int(y) - int(z) < s['y'] < int(y) + int(z)
            data)
        )