Need a strange sort method...
Gerard Flanagan
grflanagan at yahoo.co.uk
Mon Oct 16 14:37:19 EDT 2006
SpreadTooThin wrote:
> I have a list and I need to do a custom sort on it...
>
> for example:
> a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order
>
> def cmp(i,j): #to be defined in this thread.
>
> a.sort(cmp)
>
> print a
> [1,4,7,10, 2,5,8, 3,6,9]
>
> So withouth making this into an IQ test.
> Its more like
> 1 4 7 10
> 2 5 8
> 3 6 9
>
> Read that top to bottom from column 1 to column 4.
> When you get to the bottom of a column move to the next column.
> Get it?
maybe the columnise function here would help:
http://www.gflanagan.net/site/python/utils/sequtils/
from math import sqrt
for i in range(2,12):
seq = range(1,i)
numcols = int(sqrt(len(seq)))
print columnise(seq, numcols)
[(1,)]
[(1, 2)]
[(1, 2, 3)]
[(1, 3), (2, 4)]
[(1, 3, 5), (2, 4, None)]
[(1, 3, 5), (2, 4, 6)]
[(1, 3, 5, 7), (2, 4, 6, None)]
[(1, 3, 5, 7), (2, 4, 6, 8)]
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
[(1, 4, 7, 10), (2, 5, 8, None), (3, 6, 9, None)]
--------------------------
def chunk( seq, size, pad=None ):
'''
Slice a list into consecutive disjoint 'chunks' of
length equal to size. The last chunk is padded if necessary.
>>> list(chunk(range(1,10),3))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list(chunk(range(1,9),3))
[[1, 2, 3], [4, 5, 6], [7, 8, None]]
>>> list(chunk(range(1,8),3))
[[1, 2, 3], [4, 5, 6], [7, None, None]]
>>> list(chunk(range(1,10),1))
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>> list(chunk(range(1,10),9))
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>> for X in chunk([],3): print X
>>>
'''
n = len(seq)
mod = n % size
for i in xrange(0, n-mod, size):
yield seq[i:i+size]
if mod:
padding = [pad] * (size-mod)
yield seq[-mod:] + padding
def columnise( seq, numcols, pad=None ):
'''
>>> columnise(range(1,10),3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> columnise(range(1,9),3)
[(1, 4, 7), (2, 5, 8), (3, 6, None)]
>>> columnise(range(1,8),3)
[(1, 4, 7), (2, 5, None), (3, 6, None)]
'''
return zip( *chunk(seq, numcols, pad) )
-------------------------------
Gerard
More information about the Python-list
mailing list