473,734 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CODE: Generic Sort Routine

I've written a generic sort routine that will sort dictionaries,
lists, or tuples, either by a specified key or by value.

Comments welcome!

import types

def sort(container, key = None, ascending = True):
' Sort lists or dictionaries by the specified key'
t = type(container)
if t in (types.ListType , types.TupleType ):
thelist = container
else:
thelist = container.value s()
if key:
sorted = zip([getattr(item, key) for item in thelist],
thelist)
else:
sorted = list(thelist)
sorted.sort()
if ascending == False:
sorted.reverse( )
if key:
return [x[1] for x in sorted]
else:
return sorted

class simple:
name = 'simple'
def __init__(self, word):
self.word = word
def __repr__(self):
return str(self.__dict __)

def test():
# Set up the test data
line = 'now is the time for all good men to come to the aid of
their country.'
words = line.split(' ')
compareto = line.split(' ')
compareto.sort( )
assert words != compareto
objects = []
for word in words:
o = simple(word)
objects.append( o)

# Sort a list of words
test1 = sort(words)
assert test1 == compareto

# Sort a list of objects
lst = sort(objects, 'word')
test2 = []
for item in lst:
test2.append(it em.word)
assert(test2 == compareto)

# Sort a tuple of objects
tup = tuple(objects)
lst = sort(tup, 'word')
test3 = []
for item in lst:
test3.append(it em.word)
assert(test3 == compareto)

# Sort a dict of objects
d = {}
ctr = 1
for item in objects:
d[ctr] = item
ctr += 1
lst = sort(d, 'word')
test4 = []
for item in lst:
test4.append(it em.word)
assert(test4 == compareto)

# Reverse sort a dict of objects
d = {}
ctr = 1
for item in objects:
d[ctr] = item
ctr += 1
lst = sort(d, 'word', False)
test4 = []
for item in lst:
test4.append(it em.word)
compareto.rever se()
assert(test4 == compareto)

# Sort a list of numbers
lst = [5, 9, 3, 54, 6, 65.7, 2.4, 9999]
lst = sort(lst)
print lst

# Done
print "All tests passed!"

if __name__ == "__main__":
test()
Jul 18 '05 #1
1 2282
Kamilche wrote:
I've written a generic sort routine that will sort dictionaries,
lists, or tuples, either by a specified key or by value.

Comments welcome!
....snip... if key:
sorted = zip([getattr(item, key) for item in thelist],
thelist)
else:
sorted = list(thelist)

....snip...

I'd change that 'if key:' line to 'if key is not None:', so that you could
sort on other non-True values.

Andy
Jul 18 '05 #2

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

Similar topics

242
13395
by: James Cameron | last post by:
Hi I'm developing a program and the client is worried about future reuse of the code. Say 5, 10, 15 years down the road. This will be a major factor in selecting the development language. Any comments on past experience, research articles, comments on the matter would be much appreciated. I suspect something like C would be the best based on comments I received from the VB news group. Thanks for the help in advance James Cameron
40
4313
by: Elijah Bailey | last post by:
I want to sort a set of records using STL's sort() function, but dont see an easy way to do it. I have a char *data; which has size mn bytes where m is size of the record and n is the number of records. Both these numbers are known
3
1752
by: Mel | last post by:
i need to sort my table based on a "header click". is there a generic code out there that does that for me, or i have to write one for each and every table i come up with ? many thanks for your input
65
12596
by: Skybuck Flying | last post by:
Hi, I needed a method to determine if a point was on a line segment in 2D. So I googled for some help and so far I have evaluated two methods. The first method was only a formula, the second method was a piece of C code which turned out to be incorrect and incomplete but by modifieing it would still be usuable. The first method was this piece of text:
4
1251
by: ITnerd | last post by:
In the interest of code re-use, I would like to place some code in a utility class to be used by other classes. The problem is that this code requires the following snippet: for(i=0; i < tbl.Rows.Count; i++) { myDataRow = tbl.Rows; company.someNestedClass sc = new company.someNestedClass(); for(j=0; j < tbl.Columns.Count; j++) {
3
1634
by: dhussong | last post by:
I'm trying to implement a generic exception handling routine that will write information to a text file at the time the exception occurred. I am using the Microsoft Application Block for Exception Handling to write to a text file. This is working great plus I get the call stack which is an added bonus. What I really want to get is the value of parameters and variables in each method in the call stack at the time of the exception. I know I...
0
1065
by: Roger Twomey | last post by:
I am writing a Windows service which is run (and tested) at a remote location so I cannot debug issues at the actual deployment site. I know that the application is having some sort of trouble as the routines never complete. I have error checking routines in place where I THOUGHT I needed them which write to the Event log. Is there a way to write an error routine which works like an asp.net ON ERROR function in the Global.asa? IE: one...
239
10249
by: Eigenvector | last post by:
My question is more generic, but it involves what I consider ANSI standard C and portability. I happen to be a system admin for multiple platforms and as such a lot of the applications that my users request are a part of the OpenSource community. Many if not most of those applications strongly require the presence of the GNU compiling suite to work properly. My assumption is that this is due to the author/s creating the applications...
1
3903
by: raylopez99 | last post by:
I seem to get name collision between the Generic collection SortedList and C++.NET Framework collection SortedList. How to resolve? Here are the libraries that seem to clash: System::Collections::SortedList, System::Collections::Generic::SortedList, using namespace System::Collections; using namespace System::Collections::Generic; Below is a working version of the generic template SortedList, which
0
8946
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
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9182
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...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
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
6031
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
4550
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
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.