16
\$\begingroup\$

I was told that using the cmp function can be very useful in code-golf. But unfortunately, Python 3 doesn't have a cmp function.

So what's the shortest equivalent of cmp that works in python 3?

\$\endgroup\$
  • 3
    \$\begingroup\$ You should clarify that you are looking for cmp or an alternative in the context of golfing. Otherwise, this might get closed as a general programming question very quickly. \$\endgroup\$ – Martin Ender May 7 '15 at 20:10
  • \$\begingroup\$ @MartinBüttner I think this is in context of the OP's golf advice question where an answer used cmp though the question asked for Python 3. \$\endgroup\$ – xnor May 7 '15 at 20:15
  • \$\begingroup\$ @xnor I know it is, but others might not. \$\endgroup\$ – Martin Ender May 7 '15 at 20:29
  • \$\begingroup\$ If it is helpful to know, you can use cmp(a,b) in Python 2. \$\endgroup\$ – mbomb007 May 7 '15 at 22:03
35
\$\begingroup\$

Python 3 does not have cmp. For golfing, you can do

11 chars

(a>b)-(a<b)

which loses 3 chars over cmp(a,b).

Amusingly, this is also an "official" workaround. The What's New in Python 3 page says "(If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)"

| improve this answer | |
\$\endgroup\$
  • 15
    \$\begingroup\$ beware precedence problems! the actual equivalent of cmp(a,b) is ((a > b) - (a < b)) \$\endgroup\$ – Sparr May 7 '15 at 20:16
  • \$\begingroup\$ if a or b are more complex expressions - say calls to functions with very long running times, then this is very bad for your running time. Worse, if a or b contains a call to a function with side-effects, this can even change the semantic of your program. \$\endgroup\$ – Algoman May 9 '18 at 10:00
  • 1
    \$\begingroup\$ @Algoman Oh noes, running time, the most important part of code-golfing /s. If you want to avoid running functions twice, just assign them to variables beforehand (which you're probably going to end up doing anyway to save on bytes) \$\endgroup\$ – Jo King Oct 30 '18 at 11:17
  • \$\begingroup\$ I'm working on a transpiler - it reads an expression and is supposed to generate an expression out of it. That cmp in the original expression could be nested deeply. it would be very ugly and hard (if not impossible) to implement, if I were to generate the target-code like that. \$\endgroup\$ – Algoman Oct 30 '18 at 23:04
  • 1
    \$\begingroup\$ @Algoman So replace cmp(exp1,exp2) with (lambda a,b:(a>b)-(a<b))(exp1,exp2). \$\endgroup\$ – Anders Kaseorg Oct 31 '18 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.