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

  • 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?


    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.

    @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 I know it is, but others might not.

    If it is helpful to know, you can use `cmp(a,b)` in Python 2.

  • xnor

    xnor Correct answer

    6 years ago

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


    beware precedence problems! the actual equivalent of cmp(a,b) is ((a > b) - (a < b))

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

    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.

    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 So replace `cmp(exp1,exp2)` with `(lambda a,b:(a>b)-(a

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

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used