2
def compare(a, b):
    """
    Return 1 if a > b, 0 if a equals b, and -1 if a < b
    >>> compare (5, 7)
    1
    >>> compare (7, 7)
    0
    >>> compare (2, 3)
    -1
    """
jamylak
  • 128,818
  • 30
  • 231
  • 230
Jordan Ruatoe
  • 21
  • 1
  • 1
  • 2

1 Answers1

12
>>> def compare(a, b):
        return (a > b) - (a < b)


>>> compare(5, 7)
-1
>>> compare(7, 7)
0
>>> compare(3, 2)
1

A longer, more verbose way would be:

def compare(a, b):
    return 1 if a > b else 0 if a == b else -1

Which, when flattened out looks like:

def compare(a, b):
    if a > b:
        return 1
    elif a == b:
        return 0
    else:
        return -1

The first solution is the way to go, remember it is pythonic to treat bools like ints

Also note that that Python 2 has a cmp function which does this:

>>> cmp(5, 7)
-1

however in Python 3 cmp is gone, since the comparisons it is usually used for eg. list.sort are now down using a key function instead of cmp.

Community
  • 1
  • 1
jamylak
  • 128,818
  • 30
  • 231
  • 230