简体   繁体   中英

Fastest way to identify area from 2D coordinates

I have the following code:

def findRegion(lat,lon):
    '''Gets a lat between -90,90 and a lon between -180,180 and returns a character'''
    if lat >= 50:
        y='ABCD'
    elif lat >= 0:
        y='EFGH'
    elif lat <= -50:
        y='MNOP'
    else:
        y='IJKL'

    if lon <= -90:
        x='AEIM'
    elif lon <= 0:
        x='BFJN'
    elif lon <= 90:
        x='CGKO'
    else:
        x='DHLP'

    for c in y:
        if c in x:
            return c

This function gets two coordinates and returns one of the 16 sector codes shown here . The code works perfectly, but it will get called lots of times, so I'm looking for the fastest possible solution. Any suggestions are much appreciated.

This should speed the process by using the x and y to find the region in a one dimensional string. May actually be slower due to the use of clamp.

clamp = lambda n, minimum, maximum: max(min(maximum, n), minimum)

def a(lat, lon):
    ## get lat, lon sections
    sec_lat = clamp((lat+90)/45,0,3)
    sec_lon = clamp((lon+180)/90,0,3)

    ## convert two values into a 1 dimensional list value
    sec = sec_lat*4 + sec_lon

    return "MNOPIJKLEFGHABCD"[sec]

This would improve the speed a little bit by skipping the double for(which is really marginal since there is only 4 iterations per loop so a worst case of 16 character comparisons) at the end of the function. Although, I would think the major improvement is in the readability which is often more important.

def findRegion(lat, lon):
    regions = ( ('A', 'B', 'C', 'D'), ('E', 'F', 'G', 'H'), ('I', 'J', 'K', 'L'), ('M', 'N', 'O', 'P'))

    lat_index = 0;
    if lat >= 50:
        lat_index = 0
    elif lat >= 0:
        lat_index = 1
    elif lat <= -50:
        lat_index = 2
    else:
        lat_index = 3

    lon_index = 0
    if lon <= -90:
        lon_index = 0
    elif lon <= 0:
        lon_index = 1
    elif lon_index <= 90:
        lon_index = 2
    else:
        lon_index = 3

    return regions[lat_index][lon_index]

print findRegion(-45, 50)

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