Skip to content

Instantly share code, notes, and snippets.

@pfirsich
Created May 5, 2015 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfirsich/c1f5102ac8fda20b48de to your computer and use it in GitHub Desktop.
Save pfirsich/c1f5102ac8fda20b48de to your computer and use it in GitHub Desktop.
"Simulation"/"exploration" script for determining prefactors for calculations done by a friend
import re
import sys
from collections import defaultdict
class Node:
def __init__(self, string, parent = None):
self.string = string
self.parent = parent
self.children = []
def getParent(self):
return self.parent
def getDepth(self):
return (self.parent.getDepth() if self.parent != None else -1) + 1
def getIndex(self):
return self.parent.children.index(self) if self.parent != None else 0
def replace(self, maxDepth = -1, maxLen = -1):
if maxDepth == 0: return
if len(self.string) >= maxLen and maxLen > 0: return
for match in re.finditer('01', self.string):
index = match.start()
if (index + 1) % 2 == 0: # even
self.children.append(Node(self.string[:index] + "1010" + self.string[index+2:], self))
else: # odd
self.children.append(Node(self.string[:index] + "10" + self.string[index+2:], self))
self.children[-1].replace(maxDepth - 1, maxLen)
def foreach(self, func):
func(self)
for child in self.children:
child.foreach(func)
def __str__(self, depth = 0):
ret = ""
for i in xrange(depth): ret += "\t"
ret += self.string + "\n"
if len(self.children) > 0: ret += "".join(child.__str__(depth + 1) for child in self.children)
return ret
def __len__(self):
return 1 + sum(len(child) for child in self.children)
def __iter__(self):
for item in Nodeiter(self):
yield item
class Nodeiter:
def __init__(self, root):
self.linearized = []
root.foreach(lambda node: self.linearized.append(node))
def __iter__(self):
return iter(self.linearized)
m = 4
root = Node("0"*m + "1"*m)
root.replace(maxLen = 2*(m+4))
#print root
print len(root)
hist = defaultdict(int)
for node in root:
hist[node.string] += 1
resultData = []
for string, count in hist.iteritems():
depth = (next(node for node in root if node.string == string).getDepth())
resultData.append([string, count, depth])
for entry in sorted(resultData, key = lambda x : x[1], reverse = True):
print "{:25} {:10} {:10}".format(entry[0], entry[1], entry[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment