Go Back   Velocity Reviews > Newsgroups > Python
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply

Python - KeyedList

 
Thread Tools Search this Thread
Old 02-28-2009, 07:02 PM   #1
Default KeyedList


The ordered dictionary discussion made me think of another data type
which seems to be somewhat related, a kind of ordered dictionary where
the order of the items is arbitrary. One can insert items in the middle
and still have O(1) access (I think). I have provided a very basic
implementation, it could be extended to also remove items with O(1)
access. I am wondering if the idea makes sense at all and what would be
the best name for the type itself and for its methods.

Could it be that the ordered dictionary is a result of a way of
thinking which slowly extends what we currently have, while a
KeyedList or whatever we ultimately choose to name it is the kind of
data type we are really looking for? If accepted, I think this type
could be used for Knuth's dancing links style algorithms.

P.

#warning, embryonic, probably very buggy implementation

class Node:

def __init__(self, left = None, right = None, key = None, item =
None): self.left = left
self.right = right
self.key = key
self.item = item

class KeyedList:

def __init__(self):
self.first = Node()
self.last = Node()
self.last.left = self.first
self.first.right = self.last
self.D = {}

def append(self, key, item):
last = self.last
prev = last.left
x = Node(prev,last,key,item)
prev.right = x
last.left = x
self.D[key] = x

def insertafter(self,key1,key2,item):
left = self.D[key1]
right = left.right
x = Node(left,right,key2,item)
left.right =x
right.left =x
self.D[key2] = x

def iteritems(self):
x = self.first.right
while x.right:
key = x.key
yield key, self.D[key].item
x = x.right

def test():
K = KeyedList()
K.append('one','hello')
K.append('two','hello')
K.append('four','hello')
K.insertafter('two','three','hello')
for x in K.iteritems():
print x

if __name__ == '__main__':
test()


pataphor
  Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off




SEO by vBSEO 3.3.2 ©2009, Crawlability, Inc.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46