Title: Possible bug in sorting algorithm
Type: behavior Stage:
Components: Interpreter Core Versions: Python 2.7
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: David.Manowitz, tim.peters
Priority: normal Keywords:

Created on 2016-04-14 01:14 by David.Manowitz, last changed 2016-04-16 21:23 by benjamin.peterson. This issue is now closed.

Messages (2)
msg263367 - (view) Author: David Manowitz (David.Manowitz) Date: 2016-04-14 01:14
I'm trying to sort a list of tuples.  Most of the tuples are pairs of US state names.  However, some of the tuples have None instead of the 2nd name.  I want the items sorted first by the 1st element, and then by the 2nd element, BUT I want the None to count as LARGER than any name.  Thus, I want to see [('Alabama', 'Iowa'), ('Alabama', None)] rather than [('Alabama', None), ('Alabama', 'Iowa')].  I defined the following comparitor:

def cmp_keys (k1, k2):
    retval = cmp(k1[0], k2[0])
    if retval == 0:
        if k2[1] is None:
            retval = -1
        if k1[1] is None:
            retval = 1
            retval = cmp(k1[1], k2[1])
    return retval

However, once I sort using this, some of the elements are out of order.
msg263368 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2016-04-14 01:21
If that's the actual code you're using, it has a bug:  the "if k2[1] is None" test is useless, since regardless of whether it's true or false, the next `if` suite overwrites `retval`.  You probably meant

    elif k1[1] ...

instead of

    if k1[1] ...

Does that fix your problem?

If not, please augment the bug report with the _complete_ code you're actually using, a sample problematic input, the exact output you're expecting, and the exact output you're seeing instead.  We're not telepathic ;-)
Date User Action Args
2016-04-16 21:23:55benjamin.petersonsetstatus: open -> closed
resolution: not a bug
2016-04-14 01:21:33tim.peterssetnosy: + tim.peters
messages: + msg263368
2016-04-14 01:14:51David.Manowitzcreate