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

前端 未结 11 2235
借酒劲吻你
借酒劲吻你 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 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)
    

提交回复
热议问题