Velocity Reviews > sort order for strings of digits

# sort order for strings of digits

djc
Guest
Posts: n/a

 10-31-2012
I learn lots of useful things from the list, some not always welcome. No
sooner had I found a solution to a minor inconvenience in my code, than
a recent thread here drew my attention to the fact that it will not work
for python 3. So suggestions please:

TODO 2012-10-22: sort order numbers first then alphanumeric
>>> n

('1', '10', '101', '3', '40', '31', '13', '2', '2000')
>>> s

('a', 'ab', 'acd', 'bcd', '1a', 'a1', '222 bb', 'b a 4')

>>> sorted(n)

['1', '10', '101', '13', '2', '2000', '3', '31', '40']
>>> sorted(s)

['1a', '222 bb', 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
>>> sorted(n+s)

['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40',
'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']

Possibly there is a better way but for Python 2.7 this gives the
required result

Python 2.7.3 (default, Sep 26 2012, 21:51:14)

>>> sorted(int(x) if x.isdigit() else x for x in n+s)

[1, 2, 3, 10, 13, 31, 40, 101, 2000, '1a', '222 bb', 'a', 'a1', 'ab',
'acd', 'b a 4', 'bcd']

[str(x) for x in sorted(int(x) if x.isdigit() else x for x in n+s)]
['1', '2', '3', '10', '13', '31', '40', '101', '2000', '1a', '222 bb',
'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']

But not for Python 3
Python 3.2.3 (default, Oct 19 2012, 19:53:16)

>>> sorted(n+s)

['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40',
'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']

>>> sorted(int(x) if x.isdigit() else x for x in n+s)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()
>>>

The best I can think of is to split the input sequence into two lists,
sort each and then join them.

--
djc

Hans Mulder
Guest
Posts: n/a

 10-31-2012
On 31/10/12 16:17:14, djc wrote:
> Python 3.2.3 (default, Oct 19 2012, 19:53:16)
>
>>>> sorted(n+s)

> ['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40',
> 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
>
>>>> sorted(int(x) if x.isdigit() else x for x in n+s)

> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: unorderable types: str() < int()
>>>>

>>> sorted(n+s, key=lambda xx.__class__.__name__, x))

['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40',
'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
>>>

> The best I can think of is to split the input sequence into two lists,
> sort each and then join them.

That might well be the most readable solution.

Hope this helps,

-- HansM

Ian Kelly
Guest
Posts: n/a

 10-31-2012
On Wed, Oct 31, 2012 at 9:17 AM, djc <(E-Mail Removed)> wrote:
> The best I can think of is to split the input sequence into two lists, sort
> each and then join them.

In the example you have given they already seem to be split, so you
could just do:

sorted(n, key=int) + sorted(s)

If that's not really the case, then you could construct (str, int)
tuples as sort keys:

sorted(n+s, key=lambda x: ('', int(x)) if x.isdigit() else (x, -1))

Note that the empty string sorts before all numbers here, which may or
may not be desirable.

Mark Lawrence
Guest
Posts: n/a

 10-31-2012
On 31/10/2012 18:17, Dennis Lee Bieber wrote:
>
> Why -- I doubt Python 3.x .sort() and sorted() have removed the
> optional key and cmp keywords.
>

Nope. I'm busy porting my own code from 2.7 to 3.3 and cmp seems to be
very dead.

This doesn't help either.

c:\Users\Mark\Cash\Python>2to3.py
Traceback (most recent call last):
File "C:\Python33\Tools\Scripts\2to3.py", line 3, in <module>
from lib2to3.main import main
ImportError: No module named main

--
Cheers.

Mark Lawrence.

Dennis Lee Bieber
Guest
Posts: n/a

 10-31-2012
On Wed, 31 Oct 2012 16:24:21 -0600, Ian Kelly <(E-Mail Removed)>
declaimed the following in gmane.comp.python.general:

>
> Use functools.cmp_to_key for porting cmp functions. "sort(x, my_cmp)"
> becomes "sort(x, key=cmp_to_key(my_cmp))"
>
> The cmp builtin is also gone. If you need it, the suggested replacement
> for "cmp(a, b)" is "(b < a) - (a < b)".
>

OUCH... Just another reason for my to hang onto the 2.x series as
long as possible (I only installed 2.7 this summer, I'd been using
2.5... And a project at my former employment was still running 2.3 and
having conflicts with a program with a binary extension written for 2.2
-- and we couldn't find the source for the extension to rebuild it!)
--
Wulfraed Dennis Lee Bieber AF6VN
http://www.velocityreviews.com/forums/(E-Mail Removed) HTTP://wlfraed.home.netcom.com/

Steven D'Aprano
Guest
Posts: n/a

 10-31-2012
On Wed, 31 Oct 2012 15:17:14 +0000, djc wrote:

> The best I can think of is to split the input sequence into two lists,
> sort each and then join them.

According to your example code, you don't have to split the input because
you already have two lists, one filled with numbers and one filled with
strings.

But I think that what you actually have is a single list of strings, and
you are supposed to sort the strings such that they come in numeric order
first, then alphanumerical. E.g.:

['9', '1000', 'abc2', '55', '1', 'abc', '55a', '1a']
=> ['1', '1a', '9', '55', '55a', '1000', 'abc', 'abc2']

At least that is what I would expect as the useful thing to do when
sorting.

The trick is to take each string and split it into a leading number and a
trailing alphanumeric string. Either part may be "empty". Here's a pure
Python solution:

from sys import maxsize # use maxint in Python 2
def split(s):
for i, c in enumerate(s):
if not c.isdigit():
break
else: # aligned with the FOR, not the IF
return (int(s), '')
return (int(s[:i] or maxsize), s[i:])

Now sort using this as a key function:

py> L = ['9', '1000', 'abc2', '55', '1', 'abc', '55a', '1a']
py> sorted(L, key=split)
['1', '1a', '9', '55', '55a', '1000', 'abc', 'abc2']

The above solution is not quite general:

* it doesn't handle negative numbers or numbers with a decimal point;

* it doesn't handle the empty string in any meaningful way;

* in practice, you may or may not want to ignore leading whitespace,
or trailing whitespace after the number part;

* there's a subtle bug if a string contains a very large numeric prefix,
finding and fixing that is left as an exercise.

--
Steven

Steven D'Aprano
Guest
Posts: n/a

 10-31-2012
On Wed, 31 Oct 2012 19:05:17 -0400, Dennis Lee Bieber wrote:

>> The cmp builtin is also gone. If you need it, the suggested
>> replacement for "cmp(a, b)" is "(b < a) - (a < b)".
>>

> OUCH... Just another reason for my to hang onto the 2.x series as
> long as possible

On the contrary. If you are using cmp with sort, your sorts are slow, and
you should upgrade to using a key function as soon as possible.

For small lists, you may not notice, but for large lists using a
comparison function is a BAD IDEA.

Here's an example: sorting a list of numbers by absolute value.

py> L = [5, -6, 1, -2, 9, -8, 4, 3, -7, 2, -3]
py> sorted(L, key=abs)
[1, -2, 2, 3, -3, 4, 5, -6, -7, -8, 9]
py> sorted(L, lambda a, b: cmp(abs(a), abs(b)))
[1, -2, 2, 3, -3, 4, 5, -6, -7, -8, 9]

But the amount of work done is radically different. Let's temporarily
shadow the built-ins with patched versions:

py> _abs = abs
py> _abs, _cmp = abs, cmp
py> c1 = c2 = 0
py> def abs(x):
.... global c1
.... c1 += 1
.... return _abs(x)
....
py> def cmp(a, b):
.... global c2
.... c2 += 1
.... return _cmp(a, b)
....

Now we can see just how much work is done under the hood using a key
function vs a comparison function:

py> sorted(L, key=abs)
[1, -2, 2, 3, -3, 4, 5, -6, -7, -8, 9]
py> c1
11

So the key function is called once for each item in the list. But:

py> c1 = 0 # reset the count
py> sorted(L, lambda a, b: cmp(abs(a), abs(b)))
[1, -2, 2, 3, -3, 4, 5, -6, -7, -8, 9]
py> c1, c2
(54, 27)

The comparison function is called 27 times for a list of nine items (a
average of 2.5 calls to cmp per item), and abs is called twice for each
call to cmp. (Well, duh.)

If the list is bigger, it gets worse:

py> c2 = 0
py> x = sorted(L*10, lambda a, b: cmp(abs(a), abs(b)))
py> c2
592

That's an average of 5.4 calls to cmp per item. And it gets even worse as
the list gets bigger.

As your lists get bigger, the amount of work done calling the comparison
function gets ever bigger still. Sorting large lists with a comparison
function is SLOOOW.

py> del abs, cmp # remove the monkey-patched versions
py> L = L*1000000
py> with Timer():
.... x = sorted(L, key=abs)
....
time taken: 9.165448 seconds
py> with Timer():
.... x = sorted(L, lambda a, b: cmp(abs(a), abs(b)))
....
time taken: 63.579679 seconds

The Timer() context manager used can be found here:

http://code.activestate.com/recipes/577896

--
Steven

DJC
Guest
Posts: n/a

 10-31-2012
On 31/10/12 23:09, Steven D'Aprano wrote:
> On Wed, 31 Oct 2012 15:17:14 +0000, djc wrote:
>
>> The best I can think of is to split the input sequence into two lists,
>> sort each and then join them.

>
> According to your example code, you don't have to split the input because
> you already have two lists, one filled with numbers and one filled with
> strings.

Sorry for the confusion, the pair of strings was just a way of testing
variations on the input. So a sequence with any combination of strings
that can be read as numbers and strings of chars that don't look like
numbers (even if that string includes digits) is the expected input

>
> But I think that what you actually have is a single list of strings, and
> you are supposed to sort the strings such that they come in numeric order
> first, then alphanumerical. E.g.:
>
> ['9', '1000', 'abc2', '55', '1', 'abc', '55a', '1a']
> => ['1', '1a', '9', '55', '55a', '1000', 'abc', 'abc2']

Not quite, what I want is to ensure that if the strings look like
numbers they are placed in numerical order. ie 1 2 3 10 100 not 1 10 100
2 3. Cases where a string has some leading digits can be treated as
strings like any other.

> At least that is what I would expect as the useful thing to do when
> sorting.

Well it depends on the use case. In my case the strings are column and
row labels for a report. I want them to be presented in a convenient to
read sequence. Which the lexical sorting of the strings that look like
numbers is not. I want a reasonable do-what-i-mean default sort order
that can handle whatever strings are used.

>
> The trick is to take each string and split it into a leading number and a
> trailing alphanumeric string. Either part may be "empty". Here's a pure
> Python solution:
>
> from sys import maxsize # use maxint in Python 2
> def split(s):
> for i, c in enumerate(s):
> if not c.isdigit():
> break
> else: # aligned with the FOR, not the IF
> return (int(s), '')
> return (int(s[:i] or maxsize), s[i:])
>
> Now sort using this as a key function:
>
> py> L = ['9', '1000', 'abc2', '55', '1', 'abc', '55a', '1a']
> py> sorted(L, key=split)
> ['1', '1a', '9', '55', '55a', '1000', 'abc', 'abc2']
>
>
> The above solution is not quite general:
>
> * it doesn't handle negative numbers or numbers with a decimal point;
>
> * it doesn't handle the empty string in any meaningful way;
>
> * in practice, you may or may not want to ignore leading whitespace,
> or trailing whitespace after the number part;
>
> * there's a subtle bug if a string contains a very large numeric prefix,
> finding and fixing that is left as an exercise.

That looks more than general enough for my purposes! I will experiment
along those lines, thank you.

Mark Lawrence
Guest
Posts: n/a

 11-01-2012
On 31/10/2012 22:24, Ian Kelly wrote:
> On Wed, Oct 31, 2012 at 3:33 PM, Mark Lawrence <(E-Mail Removed)>wrote:
>
>> Nope. I'm busy porting my own code from 2.7 to 3.3 and cmp seems to be
>> very dead.
>>
>> This doesn't help either.
>>
>> c:\Users\Mark\Cash\Python>**2to3.py
>>
>> Traceback (most recent call last):
>> File "C:\Python33\Tools\Scripts\**2to3.py", line 3, in <module>
>> from lib2to3.main import main
>> ImportError: No module named main
>>

>
> Perhaps you have a sys.path conflict?

Correct, now fixed, thanks.

>
> Use functools.cmp_to_key for porting cmp functions. "sort(x, my_cmp)"
> becomes "sort(x, key=cmp_to_key(my_cmp))"
>
> The cmp builtin is also gone. If you need it, the suggested replacement
> for "cmp(a, b)" is "(b < a) - (a < b)".

As it's my own small code base I've blown away all references to cmp,
it's rich comparisons all the way.

>
> Cheers,
> Ian
>

--
Cheers.

Mark Lawrence.

Chris Angelico
Guest
Posts: n/a

 11-01-2012
On Thu, Nov 1, 2012 at 10:44 AM, Steven D'Aprano
<(E-Mail Removed)> wrote:
> On the contrary. If you are using cmp with sort, your sorts are slow, and
> you should upgrade to using a key function as soon as possible.
>

But cmp_to_key doesn't actually improve anything. So I'm not sure how
Py3 has achieved anything; Py2 supported key-based sorting already.

ChrisA

 Thread Tools

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post =?iso-8859-1?Q?=22Orlando_D=F6hring=22?= Python 0 05-29-2007 03:31 PM Ben C Programming 14 06-24-2006 05:09 AM nobody XML 0 06-01-2004 06:25 AM Angus Comber C Programming 7 02-05-2004 06:41 PM Navin ASP General 1 09-09-2003 07:16 AM

Advertisments