The Python Oracle

Alternative approaches to comparing values

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 Alternative Approaches To Comparing Values
00:30 Answer 1 Score 1
00:42 Accepted Answer Score 6
00:58 Answer 3 Score 0
01:07 Answer 4 Score 0
01:17 Thank you

--

Full question
https://stackoverflow.com/questions/1680...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #algorithm

#avk47



ACCEPTED ANSWER

Score 6


This problem can be greatly simplified, without loss of generality, by sorting:

def close_far(a, b, c):
  x, y, z = sorted([a, b, c])
  delta_close, delta_far = sorted([y - x, z - y])
  return delta_close <= 1 and delta_far >= 2



ANSWER 2

Score 1


def close_far(a, b, c):
    def close(x, y): return abs(x - y) <= 1
    def far(x, y): return abs(x - y) >= 2
    return (close(b, a) and far(c, a) and far(c, b) or
            close(c, a) and far(b, a) and far(b, c))

>>> close_far(1, 2, 10)
True
>>> close_far(1, 2, 3)
False
>>> close_far(4, 1, 3)
True



ANSWER 3

Score 0


Little help:

def close_far(a, b, c): return ((abs(a-c) >= 2 and abs(a-b) <= 1) and (abs(b-c) >= 2)) or ((abs(a-c) <= 1 and abs(a-b) >= 2) and (abs(b-c) >= 2))




ANSWER 4

Score 0


Here is an approach:

def close_far(a, b, c):
    return not ((is_close(a,b)==is_close(a,c)) or is_close(b,c))


def is_close(num1, num2):
    return abs(num1-num2)<=1