0

I have a binary function which returns a Boolean indicating whether the first argument is strictly less than the second argument. Can I use the sorted(my_list, key=functools.cmp_to_key(boolean_cmp)) or some variant thereof to sort this list? Or do I need to refactor the boolean_cmp function so that it returns a positive, negative, or zero integer?

Do I really need to distinguish between the greater-than case and the equal-to case?

The boolean_cmp function is written as a several methods spread out over the program. Refactoring them would be possible, but seems like more work than is necessary.

I've done a bit of experimentation and it looks like converting False to 0 and True to -1 causes sorted to sort correctly. But my experiment is only anecdotal.

BTW, I was reading Sorting HOW TO and it took me a long time to figure out that the underlying compare function needed an integer return value rather than a Boolean. In my opinion, it would have been nice if that had been clearer. [grumble]

5
  • 1
    Rather than refactor it (since you use it elsewhere) wrap it in a lambda or proper function that returns what you want to return. Commented Jun 23, 2021 at 12:58
  • @JonSG, is it sufficient to convert False to 0 and True to -1, or do I need to distinguish between the == case and the > case? Because if I need to distinguish all three cases, I cannot do this with a simple wrapper function Commented Jun 23, 2021 at 13:00
  • 2
    How about lambda a, b : 1 if boolean_cmp(a, b) else -1 if boolean_cmp(b, a) else 0? Commented Jun 23, 2021 at 13:16
  • 1
    Though I suspect lambda a, b : 1 if boolean_cmp(a, b) else -1 might be sufficient Commented Jun 23, 2021 at 13:18
  • 2
    @JonSG I suggest posting that as an answer, since I don't think there will be any better answer than that to this question. Commented Jun 23, 2021 at 15:48

1 Answer 1

1

Rather than refactor a method you already have in use, I recommend that you wrap a lambda around it that will try to return the -1, 0, 1 that functools.cmp_to_key() is hoping for.

Maybe something like:

lambda a, b : 1 if boolean_cmp(a, b) else -1 if boolean_cmp(b, a) else 0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.