view ch3ex5.py @ 24:5c2c4ce095ef

A stab at the L(p)/L(0) plot. I still don't quite get how the graphs in the Watts and Strogatz paper were generated. My results have basically the same shape, but don't converge to 0. I'm not sure how this is possible if the rewire function does not remove edges.
author Brian Neal <bgneal@gmail.com>
date Thu, 03 Jan 2013 18:41:13 -0600
parents 0326803882ad
children
line wrap: on
line source
"""Chapter 3, exercise 5.

"A drawback of hashtables is that the elements have to be hashable, which usually
means they have to be immutable. That's why, in Python, you can use tuples but
not lists as keys in a dictionary. An alternative is to use a tree-based map.
Write an implementation of the map interface called TreeMap that uses
a red-black tree to perform add and get in log time."


"""
import redblacktree


class TreeMap(object):
    """A tree-based map class."""

    def __init__(self):
        self.tree = redblacktree.Tree()

    def get(self, k):
        """Looks up the key (k) and returns the corresponding value, or raises
        a KeyError if the key is not found.

        """
        return self.tree.find(k)

    def add(self, k, v):
        """Adds the key/value pair (k, v) to the tree. If the key already
        exists, the value is updated to the new value v.

        Returns True if the pair was inserted, and False if the key already
        existed and the tree was updated.

        """
        node, inserted = self.tree.insert(k, v)
        if not inserted:
            node.value = v
        return inserted

    def remove(self, k):
        """Removes the mapping with the given key (k).
        Raises a KeyError if the mapping was not found.

        """
        result = self.tree.remove(k)
        if not result:
            raise KeyError

    def __len__(self):
        """Returns the number of mappings in the map."""
        return len(self.tree)


def main(script):
    import string
    m = TreeMap()
    s = string.ascii_lowercase

    for k, v in enumerate(s):
        m.add([k], v)

    for k in range(len(s)):
        key = [k]
        print key, m.get(key)
        m.remove(key)

    assert len(m) == 0

if __name__ == '__main__':
    import sys
    main(*sys.argv)