mbilyanov
mbilyanov

Reputation: 2521

How to return a comparison operator based on provided two values?

I would like to create a python function that once provided with two int values will return a comparison string. There are the obvious ways, of using if blocks or for and while loops. I am just curious to find out the best possible solution.

def get_comparison_operator(a, b):
    if a == b:
        op = '=='
    elif a > b:
        op = '>'
    # ... etc
    return op

A simple if-else block will run into the problem of distinguishing between == and <= or >= so probably I would go with a for loop with a break. However, as I said before, I am keen to learn the efficient way of doing this, if any.

Upvotes: 2

Views: 2872

Answers (1)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23243

You may use operator module to reduce line count, but in the end of the day you need to keep list of operations to check.

import operator

operators = [operator.eq, operator.lt, operator.gt, operator.ne]
labels = ["==", "<", ">", "!="]

def get_comparison_operator(a, b):
    for op, label in zip(operators, labels):
        if op(a, b):
            return label
    return None

Obviously check order is crucial here, if greater equal is checked before greater, second one will not have a change to be returned.

Alternative form with list of tuples, I must say table-like form looks really nice.

import operator

operators = [
    (operator.eq, "=="), 
    (operator.lt, "<"),
    (operator.gt, ">"),
    (operator.ne, "!=")
]

def get_comparison_operator(a, b):
    for op, label in operators:
        if op(a, b):
            return label
    return None

Obviously, eq/lt/gt is fairly trivial, since 3 possibilities covers 100% of cases and they are mutually exclusive. Maybe for some weirder operators this approach makes more sense.

Upvotes: 5

Related Questions