By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,171 Members | 776 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,171 IT Pros & Developers. It's quick & easy.

Re: Customizing sequence types

P: n/a
On Sun, Nov 16, 2008 at 8:16 AM, Mr. SpOOn <mr********@gmail.comwrote:
Hi,
I'm trying to create a class which inherit a list to change some behavior.
This list should contain other instance objects and has to manage
these instances in a particular way.

1) I need to sort this elements in this list, but they must be sorted
using an instance variable. What does Python use to sort elements? I
mean, there is a __sort__ method in the class list or it just uses
comparison operators? In this case, shall I just redefine this
operators in the element classes?
It uses the comparison operators. IIRC, at a minimum it needs __lt__
and __eq__ to be defined on the elements.
>
2) I need to have just unique elements. Maybe this is related to first
question (or maybe not). Again, to estabilish the uniqueness of an
element I have to use an instance variable. I think I have to rewrite
both the methods append() and __contains__(), but I'm not sure how.

For the first one I did:

def append(self, element):
if element in self:
pass
else:
list.append(self, element)
You should probably use the `bisect` module
(http://docs.python.org/library/bisect.html) for searching and
inserting into the list as it takes advantage of and ensures that the
list keeps sorted. It also means that __contains__ and some other
operations become O(log N) rather than O(N).

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
>
It seems right to me, but I have no idea what to do with __contains__()

Suggestion?
--
http://mail.python.org/mailman/listinfo/python-list
Nov 16 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.