473,903 Members | 3,914 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need a strange sort method...

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?

Oct 16 '06 #1
20 1690
"SpreadTooT hin" <bj********@gma il.comwrites:
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]
def k(n): return (n-1) % 3, (n-1) // 3
a.sort(key=k)
Oct 16 '06 #2
On 16 Oct 2006 11:13:08 -0700, SpreadTooThin <bj********@gma il.comwrote:
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
>>a = [1,2,3,4,5,6,7,8 ,9,10]
a.sort(key=la mbda item: (((item-1) %3), item))
a
[1, 4, 7, 10, 2, 5, 8, 3, 6, 9]

--
Cheers,
Simon B
si***@brunningo nline.net
http://www.brunningonline.net/simon/blog/
Oct 16 '06 #3
SpreadTooThin wrote:
I have a list and I need to do a custom sort on it...
Its more like
1 4 7 10
2 5 8
3 6 9
that's trivial to do with slicing, of course. what makes you think you
need to do this by calling the "sort" method ?

</F>

Oct 16 '06 #4
On 10/16/06, Simon Brunning <si***@brunning online.netwrote :
>a = [1,2,3,4,5,6,7,8 ,9,10]
a.sort(key=lam bda item: (((item-1) %3), item))
a
[1, 4, 7, 10, 2, 5, 8, 3, 6, 9]
Re-reading the OP's post, perhaps sorting isn't what's required:
>>a[::3] + a[1::3] + a[2::3]
[1, 4, 7, 10, 2, 5, 8, 3, 6, 9]

--
Cheers,
Simon B
si***@brunningo nline.net
http://www.brunningonline.net/simon/blog/
Oct 16 '06 #5

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(se q)))
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(ra nge(1,10),3))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>list(chunk(ra nge(1,9),3))
[[1, 2, 3], [4, 5, 6], [7, 8, None]]
>>list(chunk(ra nge(1,8),3))
[[1, 2, 3], [4, 5, 6], [7, None, None]]
>>list(chunk(ra nge(1,10),1))
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>list(chunk(ra nge(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(ran ge(1,10),3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>columnise(ran ge(1,9),3)
[(1, 4, 7), (2, 5, 8), (3, 6, None)]
>>columnise(ran ge(1,8),3)
[(1, 4, 7), (2, 5, None), (3, 6, None)]
'''
return zip( *chunk(seq, numcols, pad) )
-------------------------------

Gerard

Oct 16 '06 #6

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?
It's a little vague, but i'm supposing that if you have an 11 in a the
order will be:
[1,4,7,10, 2,5,8,11, 3, 6,9]
If this holds then your order is based on x%3. You place first all x
for which x%3 == 1, then x%3 == 2, and last x%3 == 0. And among these
three group you use "natural" order.
so:
def yourcmp(i,j):
ri = i%3
rj = j%3
if ri == rj: return i.__cmp__(j)
elif ri == 0: return 1
elif rj == 0: return -1
else: return ri.__cmp__(rj)
This works with your example, and with my assumption, feel free to
"optimize" the if/elif block.

However you shuold pay attention to the 0 behavior.
a = range(11)
a.sort(yourcmp)
print a
[1, 4, 7, 10, 2, 5, 8, 0, 3, 6, 9]

Oct 16 '06 #7
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.
Well, if you're willing to give up doing it in a cmp() method,
you can do it as such:
>>a.sort()
chunk_size = 3
[a[i::chunk_size] for i in range(chunk_siz e)]
[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]

If you need it in a flat list, rather than as a list of
chunk_size lists (which are handy for iterating over in many
cases), there are ways of obtaining it, such as the hackish
>>sum([a[i::chunk_size] for i in range(chunk_siz e)], [])
[1, 4, 7, 10, 2, 5, 8, 3, 6, 9]

There are likely good recipes for flattening a list. I just
happen not to have any at my fingertips.

I'm not sure it's possible to do in a cmp() method, given that it
requires apriori knowledge of the dataset (are the numbers
contiguous?). Unless, of course, you have such a list...

However, as a benefit, this method should work no matter what the
list contains, as long as they're comparable to each other for an
initial sorting:
>>a = [chr(ord('a') + i) for i in range(10)]
# a.sort() if it were needed
a
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>sum([a[i::chunk_size] for i in range(chunk_siz e)], [])
['a', 'd', 'g', 'j', 'b', 'e', 'h', 'c', 'f', 'i']
-tkc


Oct 16 '06 #8

Fredrik Lundh wrote:
SpreadTooThin wrote:
I have a list and I need to do a custom sort on it...
Its more like
1 4 7 10
2 5 8
3 6 9

that's trivial to do with slicing, of course. what makes you think you
need to do this by calling the "sort" method ?

</F>
You are of course correct.. There might be a way to do this with
slicing
and i % 3

Oct 16 '06 #9
On 2006-10-16, Tim Chase <py*********@ti m.thechases.com wrote:
If you need it in a flat list, rather than as a list of
chunk_size lists (which are handy for iterating over in many
cases), there are ways of obtaining it, such as the hackish
>sum([a[i::chunk_size] for i in range(chunk_siz e)], [])
[1, 4, 7, 10, 2, 5, 8, 3, 6, 9]

There are likely good recipes for flattening a list. I just
happen not to have any at my fingertips.
Actually, there isn't a good recipe in Python for flattening a
list. They all come out tasting like Circus Peanuts (Turkish
Delight for you non-Yanks).

--
Neil Cerutti
Oct 16 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1109
by: Aaron | last post by:
I have 2 listbox server controls on my page that I've written a few js functions to move the options between them. All works fine, except when I call my function to re-sort the lists. After the items are removed from one list and added to another, the following is called passing the "list to be sorted" in as an object. If I put a simple alert in after the sort method, it works fine. Once I remove the alert, I get the "Unspecified...
9
2214
by: Wescotte | last post by:
Here is a small sample program I wrote in PHP to help illustrates problem I'm having. The data base is using DB2 V5R3M0. The client is WinXP machine using the iSeries Client Access Driver ver 10.00.04.00 to connect to the database. The problem is that executing the exact same SQL select statement more than twice int a row stops produces results. The first two instances will always produce the correct results but after that it will simply...
5
3798
by: Learner | last post by:
Hello, Here is the code snippet I got strucked at. I am unable to convert the below line of code to its equavalent vb.net code. could some one please help me with this? static public List<RoleData> GetRoles() { return GetRoles(null, false); }
10
1271
by: Dustan | last post by:
I'm hiding some of the details here, because I don't want to say what I'm actually doing. I have a special-purpose class with a __cmp__ method all set up and ready to go for sorting. Then I have a special class that is based on the builtin type list (though I didn't actually inherit list; I probably should). When I create an instance with 2 or more items, and attempt to sort it, I get this strange error message: Traceback (most recent...
5
3926
by: fade | last post by:
Good afternoon, I need some advice on the following: I've got a class that has a member std::vector<CStringm_vFileName and a member CString m_path; The vector contains a bunch of filenames with no path included (no C:\...) eg: my_file2.jpg, my_file1.bmp, etc... and m_path stores the path, eg: C:\folder1 I want to sort this vector according to different criterion, such as
2
1502
by: Richard Jebb | last post by:
We are trying to use the API of a Win32 app which presents the API as a COM interface. The sample VB code for getting and setting the values of custom data fields on an object shows a method named Value(): getter obj.Value("myfield") setter obj.Value("myfield") = newvalue Using Python 2.5 and PythonWin we can get data from data fields using the identical syntax
7
2395
by: abracadabra | last post by:
I am reading an old book - Programming Pearls 2nd edition recently. It says, "Even though the general C++ program uses 50 times the memory and CPU time of the specialized C program, it requires just half the code and is much easier to extend to other problems." in a sorting problem of the very first chapter. I modified the codes in the answer part, ran it and found it is almost the contrary case. The qsortints.c is the C code that uses...
1
1105
by: shapper | last post by:
Hello, I have the following code line: .... Return Array.Sort(categories.ToArray) .... categories is a Generic.List(Of String) I get the error "Expression does not produce a value". Why? What is
2
1351
by: almurph | last post by:
H ieveryone, Can you help me please? I am trying to sort a hashtable but get the error: "Cannot implicity convert type void to System.Collections.ArrayList" I am doing the following: ****BEGIN CODE****
0
9999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10500
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8048
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7206
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5894
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6088
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3324
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.