How can I use cmp(a,b) with Python3?

16

5

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?

xaxa

Posted 2015-05-07T20:04:05.027

Reputation: 221

3You 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. – Martin Ender – 2015-05-07T20:10:50.907

@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.

– xnor – 2015-05-07T20:15:17.017

@xnor I know it is, but others might not. – Martin Ender – 2015-05-07T20:29:47.533

If it is helpful to know, you can use cmp(a,b) in Python 2. – mbomb007 – 2015-05-07T22:03:08.917

Answers

34

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).)"

xnor

Posted 2015-05-07T20:04:05.027

Reputation: 115 687

15beware precedence problems! the actual equivalent of cmp(a,b) is ((a > b) - (a < b)) – Sparr – 2015-05-07T20:16:11.477

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. – Algoman – 2018-05-09T10:00:50.110

1@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) – Jo King – 2018-10-30T11:17:15.927

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. – Algoman – 2018-10-30T23:04:37.780

But mostly, I think computing something beforehand and storing the result in a variable is bad style - that's how you program in assembler or COBOL. In higher-level languages, you should be able to nest things. So the removal of the cmp function is a step in the wrong direction. – Algoman – 2018-10-30T23:16:02.037

1@Algoman So replace cmp(exp1,exp2) with (lambda a,b:(a>b)-(a<b))(exp1,exp2). – Anders Kaseorg – 2018-10-31T18:24:04.927

@AndersKaseorg that's a good idea. Still rather ugly in comparison to plain cmp, but better - Thanks :-). I will probably just put my own cmp function into a library and use that, though. :-/ – Algoman – 2018-11-03T21:59:32.150