# # from lecture 5: methods to enumerate all combinations of L variables each taking on values # between 1..k # NextLeaf to enumerate all combinations in odometer order # NextVertex, Bypass to enumerate all combinations in preorder search tree # with option to bypass a subtree # def NextLeaf(a, L, k): # len(a) = L, each a[i] in range 1..k # enumerates k^L values on successive calls in odometer order for i in reversed(xrange(L)): if (a[i] < k): a[i] += 1 break else: a[i] = 1 return a def NextVertex(a, i, L, k): # advances to next vertex in preorder traversal of search tree with k^L leaves # i >= 0 is level (depth) in tree, i < L => non-leaf vertex # yields (next vertex a, level of a) if (i < L): a[i] = 1 return (a, i+1) else: for j in reversed(xrange(L)): if (a[j] < k): a[j] += 1 return (a, j+1) a[j] = 0 return (a, 0) def Bypass(a, i, L, k): # skip children of an interior node at level i for j in reversed(xrange(i)): if (a[j] < k): a[j] += 1 return (a, j+1) a[j] = 0 return (a, 0) if __name__ == "__main__": # Testing code print "All leafs:" s = [1,1,1] while True: print s s = NextLeaf(s,3,2) if s == [1,1,1]: break print "\nAll nodes:" s = [0,0,0] level = 0 while True: print s, level s, level = NextVertex(s,level,3,2) if level == 0: break print "\nPrune Interior:" s = [0,0,0] level = 0 while True: print s, level if ((level == 2) and (s[0] != s[1])): s, level = Bypass(s,level,3,2) else: s, level = NextVertex(s,level,3,2) if level == 0: break print "\nPrune Exterior:" s = [0,0,0] level = 0 while True: print s, level if ((level == 2) and (s[0] == s[1])): s, level = Bypass(s,level,3,2) else: s, level = NextVertex(s,level,3,2) if level == 0: break raw_input("Press [Enter] to quit")