#! /usr/bin/python ## map from binary code to integer, growing from the HEAD, appending bits to tail. ## David MacKay Dec 2005 from Fibo import * ## supplies Fibonacci import sys, string from Numeric import * verbose=0 fibs=Fibonacci() #for i in range(6): # print i,fibs.calculate(i) sortbynumber=1 class node: def __init__(self, index, name="", length=0,invP=1): self.index = index self.name = name self.length = length self.invP = invP ## P(stop now) = 1/2 self.iPX = invP * 2.0 n = self.index ## P(child,0) = 1/2 * (n+1)/(2n+1) self.iP0 = self.iPX * (2 * n + 1.0)/(n+1.0) self.iP1 = self.iPX * (2 * n + 1.0)/(n) allnodes.append( self ) def __cmp__(self, other): if sortbynumber : return cmp(self.index, other.index) else : return cmp(self.name, other.name) def report(self): if (self.index == 1 ) : print '#N Len\tCodewrd' print '%-4d %-3d %-10s 1/%-10.5g \t%d' % \ (self.index,self.length,self.name+"_",self.iPX, self.index*(self.index+1)) def child(self,type) : length = self.length if(type==0): n = 2 * self.index name = self.name + '0' predecessor = self.index length = self.length + 1 invP = self.iP0 else: n = 2 * self.index + 1 name = self.name + '1' length = self.length + 1 invP = self.iP1 return node(n,name,length,invP) pass pass if(0): ## Read from stdin. Make first node one = node( 1 ) for line in sys.stdin.readlines(): if line[0] != '#' : words = string.split(line) for w in words : wl = list(w) wl.reverse() ch = one for s in wl : ch = ch.child(int(s)) print ch.index pass pass pass pass if __name__ == '__main__': ## make a big table of all integers c=[] maxlength = 11 for length in range(maxlength+2) : # print length c.append( [] ) allnodes = [] ## Make first node one = node( 1 ) c[0] = [one] ## extend all words generated thus far for length in range(maxlength) : if verbose: print "extending all with length",length for n in c[length] : for suffix in [0,1] : ch = n.child(suffix) chlen = ch.length c[chlen].append( ch ) if verbose: print "# sorted by length" for length in range(maxlength) : for n in c[length] : n.report() allnodes.sort() print "# sorted by index" cum = 0.0 for n in allnodes : cum += 1.0/(n.iPX) pass print "# CUM:", cum for n in allnodes : n.report() pass pass pass