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