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

<pre><code>def get_comparison_operator(a, b):
    if a == b:
        op = '=='
    elif a &gt; b:
        op = '&gt;'
    # ... etc
    return op
</code></pre>

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

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

<pre><code>import operator

operators = [operator.eq, operator.lt, operator.gt, operator.ne]
labels = ["==", "&lt;", "&gt;", "!="]

def get_comparison_operator(a, b):
    for op, label in zip(operators, labels):
        if op(a, b):
            return label
    return None
</code></pre>

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

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

<pre><code>import operator

operators = [
    (operator.eq, "=="), 
    (operator.lt, "&lt;"),
    (operator.gt, "&gt;"),
    (operator.ne, "!=")
]

def get_comparison_operator(a, b):
    for op, label in operators:
        if op(a, b):
            return label
    return None
</code></pre>

<p>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.</p>

python