How do I find the difference between two values without knowing which is larger?

前端 未结 11 2210
借酒劲吻你
借酒劲吻你 2020-12-11 14:22

I was wondering if there was a function built into Python that can determine the distance between two rational numbers but without me telling it which number is larger. e.g.

相关标签:
11条回答
  • 2020-12-11 14:54

    If you have an array, you can also use numpy.diff:

    import numpy as np
    a = [1,5,6,8]
    np.diff(a)
    Out: array([4, 1, 2])
    
    0 讨论(0)
  • 2020-12-11 14:55

    So simple just use abs((a) - (b)).

    will work seamless without any additional care in signs(positive , negative)

    def get_distance(p1,p2):
         return abs((p1) - (p2))
    
    get_distance(0,2)
    2
    
    get_distance(0,2)
    2
    
    get_distance(-2,0)
    2
    
    get_distance(2,-1)
    3
    
    get_distance(-2,-1)
    1
    
    0 讨论(0)
  • 2020-12-11 14:57

    Just use abs(x - y). This'll return the net difference between the two as a positive value, regardless of which value is larger.

    0 讨论(0)
  • 2020-12-11 15:00

    If you don't need a signed integer, this is an alternative that uses a slightly different approach, is easy to read and doesn't require an import:

    def distance(a, b):
      if a > 0 and b > 0:
        return max(a, b) - min(a, b)
      elif a < 0 and b < 0:
        return abs(a - b)
      elif a == b:
        return 0
      return abs(a - 0) + abs(b - 0)
    
    0 讨论(0)
  • 2020-12-11 15:06

    abs(x-y) will do exactly what you're looking for:

    In [1]: abs(1-2)
    Out[1]: 1
    
    In [2]: abs(2-1)
    Out[2]: 1
    
    0 讨论(0)
  • 2020-12-11 15:06

    You can try: a=[0,1,2,3,4,5,6,7,8,9];

    [abs(x[1]-x[0]) for x in zip(a[1:],a[:-1])]

    0 讨论(0)
提交回复
热议问题