infectmac.com
python tree

I implement a simple tree with the DFS and BFS defined using python generators.

class Tree:
    def __init__(self,data):
        self.children = []
        self.data = data

    def dfs(self):
        yield self
        if len(self.children) == 0:
            return
        for child in self.children:
            for c in child.dfs():
                yield c

    def bfs(self):
        yield self
        queue = list(self.children)
        while len(queue) > 0:
            first = queue[0]
            queue = queue[1:]
            queue.extend(first.children)
            yield first

if __name__ == "__main__":
    root = Tree(-1)
    root.children = [Tree(i) for i in range(5)]
    for i in range(5):
        root.children[i].children = [Tree(i*j) for j in range(3)]

    #-1,0,0,0,0...
    for node in root.dfs():
        print node.data

    print
    print

    #-1,0,1,2,3,4,0,0,0,0,1,2,0,2,4...
    for node in root.bfs():
        print node.data
chipmark2rss

I have been busy this past week but I got a chance to create a new chipmark feature. It's not actually on your our https://www.chipmark.com server but I wrote an app Google App Engine that downloads your public bookmarks and puts them in an RSS feed. The downside of the app is that users must provide there username and password. It would be nice if we implemented OAuth on Chipmark so third party apps could be allowed access to the account without the user having to give their password away to the app. One goal this past year was to implement mashups with chipmark. Currently, we do not have a method that allow users to expose their public chipmarks. For right now the app engine app is the only way to embed a feed of your chipmarks in a website. Take a look at the sidebar and you'll see some of my recent chipmarks.

I should mention I thought of doing this after seeing this in my feed reader yesterday: remote torrent.

A simple stack machine

A lot of popular virtual machines are stack based. The instruction sets take their inputs from a stack and then place their outputs on the same stack. It's pretty simple at face value but the virtual machines end up doing a lot of fancy things behind the scenes to make the code run fast.

Today I implement a REALLY REALLY BASIC stack based virtual machine that does basic math.

s = []

def e(cmd):
    global s
    f={'add' : 's.append(s.pop()+s.pop())',
       'dup' : 's.append(s[-1])',
       'sub' : 's.append(s.pop()-s.pop())',
       'mul' : 's.append(s.pop()*s.pop())',
       'div' : 's.append(s.pop()/s.pop())',
       'peak' : 'print s[-1]',
       'out' : 'print s.pop()'
       }[cmd]
    exec(f)

s.append(5)
s.append(1)
e('add')
e('dup')
s.append(12)
e('mul')
e('sub')
e('peak')
e('out')

The key of the dictionary is the instruction and the value defines what the instruction does.