Python:如何计算单元格之间的距离?

时间:2019-03-28 10:50:14

标签: python

让我们假设要计算正方形网格5x5中像元之间的距离。两个像元之间的距离为100m

网格的每个单元格的数字在024之间

0   1  2  3  4
5   6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24 

例如:

distance between cell 0 and 3 is 300
distance between cell 2 and 7 is 100
distance between cell 11 and 19 is 400

我必须计算xy单元位置之间的距离。

gs = 5 ## Cells per side
S = gs*gs ## Grid Size
r0 = 100 ## distance between two cells

for i in range(0, S):
    for j in range(0, S):
        if i == j: continue
        x = int(floor(i/gs))
        y = int(floor(j/gs))
        dist = x*r0 + abs(j-i)*r0

但这不是正确的解决方案

5 个答案:

答案 0 :(得分:1)

/**
 * Attempts to access a non-Google API using a constructed service
 * object.
 *
 * If your add-on needs access to non-Google APIs that require OAuth,
 * you need to implement this method. You can use the OAuth1 and
 * OAuth2 Apps Script libraries to help implement it.
 *
 * @param {String} url         The URL to access.
 * @param {String} method_opt  The HTTP method. Defaults to GET.
 * @param {Object} headers_opt The HTTP headers. Defaults to an empty
 *                             object. The Authorization field is added
 *                             to the headers in this method.
 * @return {HttpResponse} the result from the UrlFetchApp.fetch() call.
 */
function accessProtectedResource(url, method_opt, headers_opt) {
  var service = getOAuthService();
  var maybeAuthorized = service.hasAccess();
  if (maybeAuthorized) {
    // A token is present, but it may be expired or invalid. Make a
    // request and check the response code to be sure.

    // Make the UrlFetch request and return the result.
    var accessToken = service.getAccessToken();
    var method = method_opt || 'get';
    var headers = headers_opt || {};
    headers['Authorization'] =
        Utilities.formatString('Bearer %s', accessToken);
    var resp = UrlFetchApp.fetch(url, {
      'headers': headers,
      'method' : method,
      'muteHttpExceptions': true, // Prevents thrown HTTP exceptions.
    });

    var code = resp.getResponseCode();
    if (code >= 200 && code < 300) {
      return resp.getContentText("utf-8"); // Success
    } else if (code == 401 || code == 403) {
       // Not fully authorized for this action.
       maybeAuthorized = false;
    } else {
       // Handle other response codes by logging them and throwing an
       // exception.
       console.error("Backend server error (%s): %s", code.toString(),
                     resp.getContentText("utf-8"));
       throw ("Backend server error: " + code);
    }
  }

  if (!maybeAuthorized) {
    // Invoke the authorization flow using the default authorization
    // prompt card.
    CardService.newAuthorizationException()
        .setAuthorizationUrl(service.getAuthorizationUrl())
        .setResourceDisplayName("Login to ....")
        .throwException();
  }
}

/**
 * Create a new OAuth service to facilitate accessing an API.
 * This example assumes there is a single service that the add-on needs to
 * access. Its name is used when persisting the authorized token, so ensure
 * it is unique within the scope of the property store. You must set the
 * client secret and client ID, which are obtained when registering your
 * add-on with the API.
 *
 * See the Apps Script OAuth2 Library documentation for more
 * information:
 *   https://github.com/googlesamples/apps-script-oauth2#1-create-the-oauth2-service
 *
 *  @return A configured OAuth2 service object.
 */
function getOAuthService() {
  return OAuth2.createService('auth')
      .setAuthorizationBaseUrl('https://app.ss.io/oauth/authorize')
      .setTokenUrl('https://api.ss.io/oauth/token')
      .setClientId('2361c9fbc5ba4b88813a3ef')
      .setClientSecret('f5d3a04f4asda30a52830e230e43727')
      .setScope('1')
      .setCallbackFunction('authCallback')
      .setCache(CacheService.getUserCache())
      .setPropertyStore(PropertiesService.getUserProperties());
}

/**
 * Boilerplate code to determine if a request is authorized and returns
 * a corresponding HTML message. When the user completes the OAuth2 flow
 * on the service provider's website, this function is invoked from the
 * service. In order for authorization to succeed you must make sure that
 * the service knows how to call this function by setting the correct
 * redirect URL.
 *
 * The redirect URL to enter is:
 * https://script.google.com/macros/d/<Apps Script ID>/usercallback
 *
 * See the Apps Script OAuth2 Library documentation for more
 * information:
 *   https://github.com/googlesamples/apps-script-oauth2#1-create-the-oauth2-service
 *
 *  @param {Object} callbackRequest The request data received from the
 *                  callback function. Pass it to the service's
 *                  handleCallback() method to complete the
 *                  authorization process.
 *  @return {HtmlOutput} a success or denied HTML message to display to
 *          the user. Also sets a timer to close the window
 *          automatically.
 */
function authCallback(callbackRequest) {
  var authorized = getOAuthService().handleCallback(callbackRequest);
  if (authorized) {
    return HtmlService.createHtmlOutput(
      'Success! <script>setTimeout(function() { top.window.close() }, 1);</script>');
  } else {
    return HtmlService.createHtmlOutput('Denied');
  }
}

/**
 * Unauthorizes the non-Google service. This is useful for OAuth
 * development/testing.  Run this method (Run > resetOAuth in the script
 * editor) to reset OAuth to re-prompt the user for OAuth.
 */
function resetOAuth() {
  getOAuthService().reset();
}

答案 1 :(得分:0)

您应该考虑坐标而不是单元格编号

gs = 5 ## Cells per side
S = gs*gs ## Grid Size
r0 = 100 ## distance between two cells

for i in range(0, S):
    for j in range(0, S):
        if i == j: continue
           xi = int(i/gs)
           yi = i % gs
           xj = int(j/gs)
           yj = j % gs
           dist = r0 * (abs(xi-xj) + abs(yi-yj))

答案 2 :(得分:0)

这是一种实现方法:

r = 100

grid = ((0,   1,  2,  3,  4),
        (5,   6,  7,  8,  9),
        (10, 11, 12, 13, 14),
        (15, 16, 17, 18, 19),
        (20, 21, 22, 23, 24))

def coord(n):
    for x, line in enumerate(grid):
        if n not in line:
            continue
        y = line.index(n)
        return x, y

def dist(n, m):
        xn, yn = coord(n)
        xm, ym = coord(m)
        return r * (abs(xn - xm) + abs(yn - ym))

print(dist(0, 3))  # 300
print(dist(2, 7))  # 100
print(dist(11, 19)) # 400

想法是先获取数字的坐标,然后计算“距离”。

答案 3 :(得分:0)

这应该为您工作

n = 5 # row length in array

def distance(a, b):
    distance = (abs(a // n - b // n) + abs(a % n - b % n)) * 100
    return "distance between cell %s and %s is %s" % (a, b, distance)

print(distance(0, 3))
print(distance(2, 7))
print(distance(11, 19))

输出:

distance between cell 0 and 3 is 300
distance between cell 2 and 7 is 100
distance between cell 11 and 19 is 400

其中ab是您的单元格,而n是数组中行的长度,在您的示例中是5

答案 4 :(得分:0)

我们只需要获取每个数字的号。然后将两者的差值b / w乘以100即可得到答案

def get_row_col(num):
    for i,g in enumerate(grid):
        if num in g:
            col = g.index(num)
            row = i
    return row, col

num1 = get_row_col(11)
num2 = get_row_col(19)
print (abs(num1[0] - num2[0])*100) + (abs(num1[1]-num2[1])*100)

可以增强此代码以检查是否存在数字。