0

Here's the issue, I'm using the sorted function to arrange a list of alpha-numeric strings. The said strings have to numbers in them separated by a letter.

For instance: sortqns(['s1q1', 's10q1', 's1q2', 's10q10', 's10q2'])

def cmpqn(a, b):
    if len(a) > len(b):
      return 1
    if len(a) < len(b):
      return -1
    if len(a) == len(b):
      return 0

def sortqns(qnlist):
    new = sorted(qnlist, cmp=cmpqn) 
    return new

Returns ['s1q1', 's1q2', 's10q1', 's10q2', 's10q10']

My problem is sorting the second digit:

sortqns(['s12q1', 's1q2', 's1q1'])

Returns ['s1q2', 's1q1', 's12q1']

Instead of:

Returning ['s1q1', 's1q2', 's12q1']

In the first example my desired return would be off if the first two items were swapped as well.

San4ez
  • 8,091
  • 4
  • 41
  • 62
tijko
  • 7,599
  • 11
  • 44
  • 64

1 Answers1

5

The sorting algorithm in list is stable. Stable sorting algorithms maintain the relative order of records with equal keys. Therefore, in your code, when two element have the same length, they will appear in the result maintained their relative order.

I think the following solution is helpful.

def sortqns(qnlist):
    return sorted(qnlist, key = lambda x: (len(x), x))
Adonis Ling
  • 131
  • 3
  • Using a `key` function rather than a `cmp` function is more efficient too (since the function is only called `O(n)` times, rather than `O(n*log(n))` times). – Blckknght Aug 14 '13 at 05:11