Store Variables – Retrieve Variables in Python + Python Implementation of Nodes & Trees

Store Variables – Retrieve Variables

# Store
>>> import cPickle
>>> sam = range(4)
>>> cPickle.dump(sam, open ( "sam.pkl" , "w" ))

# Revive
>>> sam = cPickle.load(open ( "sam.pkl"))

Implementation of Nodes

class Node:
 def __init__(self, value, next=None):
 self.value = value = next
You construct a list by specifying all the nodes:
>>> L = Node("a", Node("b", Node("c", Node("d"))))

Implementation of Tree

class Tree:
 def __init__(self, left, right):
 self.left = left
 self.right = right

You can use the Tree class like this:
>>> t = Tree(Tree("a", "b"), Tree("c", "d"))
>>> t.right.left

Implementation of Multiway Tree Class

class Tree:
 def __init__(self, kids, next=None): = self.val = kids = next
The separate val attribute here is just to have a more descriptive name when supplying a value
(such as 'c') instead of a child node. Feel free to adjust this as you want, of course. Here’s an example of
how you can access this structure:
>>> t = Tree(Tree("a", Tree("b", Tree("c", Tree("d")))))


When prototyping (or even finalizing) data structures such as trees, it can be useful to have a flexible class
that will allow you to specify arbitrary attributes in the constructor. In these cases, the “Bunch” pattern
(named by Alex Martelli in the Python Cookbook) can come in handy. There are many ways of
implementing it, but the gist of it is the following:

class Bunch(dict):
 def __init__(self, *args, **kwds):
 super(Bunch, self).__init__(*args, **kwds)
 self.__dict__ = self

There are several useful aspects to this pattern. First, it lets you create and set arbitrary attributes by
supplying them as command-line arguments:

>>> x = Bunch(name="Jayne Cobb", position="Public Relations")
'Jayne Cobb'

Second, by subclassing dict, you get lots of functionality for free, such as iterating over the keys/attributes
or easily checking whether an attribute is present. Here’s an example:

>>> T = Bunch
>>> t = T(left=T(left="a", right="b"), right=T(left="c"))
>>> t.left
{'right': 'b', 'left': 'a'}
>>> t.left.right
>>> t['left']['right']
>>> "left" in t.right
>>> "right" in t.right

This pattern isn’t useful only when building trees, of course. You could use it for any situation where you’d
want a flexible object whose attributes you could set in the constructor.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s