Complex 'compare'

Chris Angelico rosuav at gmail.com
Tue Dec 18 06:03:40 EST 2018


On Tue, Dec 18, 2018 at 9:52 PM Frank Millman <frank at chagford.com> wrote:
> I need to know if one row is greater than or less than the other. The sort
> sequence can be complex - one or more columns, each of which can be sorted
> ascending or descending.
>
> Below is the function I have come up with. Can anyone see any problem with
> it, or suggest a better way to do it?

I'm not sure what the difference is between "compare_type" and "desc".
You have four options here:

* gt, desc
    True if source_col is None else source_col < target_col
* gt, not desc
    False if source_col is None else source_col > target_col
* lt, desc
    False if source_col is None else source_col > target_col
* lt, not desc
    True if source_col is None else source_col < target_col

The way this is currently coded, these come in two perfect pairs. The
"desc" flag is exactly the same as inverting the gt/lt status, or if
you prefer, toggling gt/lt is exactly the same as inverting every
comparison. My best understanding of it is that your rich comparison
function is unable to express the sentiment "they're equal", which
then has to be handled separately; but I don't know what would happen
if you're working with values that aren't totally ordered.

If you can't in any way simplify the overall logic, and you CAN assume
a total ordering (which means that exactly one of "a < b", "a == b",
"a > b" will be true), then what I'd recommend is doing a bit of
algebra. Something like:

for pos, desc in order:
    if compare_type == "lt": desc = not desc
    source_col = source_row[pos]
    target_col = target_row[pos]
    if source_col == target_col: continue
    if source_col is None: return False
    return (source_col < target_col) == desc

I may have the logic wrong, as I'm not sure I fully understand your
code, but this is the kind of way that I'd try to do it.

ChrisA



More information about the Python-list mailing list