Skip to content

Instantly share code, notes, and snippets.

@austinschwartz
Created March 1, 2017 20:48
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 austinschwartz/e8d41a1211683565aac2688e89155bb1 to your computer and use it in GitHub Desktop.
Save austinschwartz/e8d41a1211683565aac2688e89155bb1 to your computer and use it in GitHub Desktop.
Generates balanced brackets of size n
# http://dl.acm.org/citation.cfm?id=357091
import random, sys
class Generator:
def __init__(self):
self.r = 0
self.k = 0
def open(self):
print("{", end = '')
self.r = self.r + 1
self.k = self.k - 1
def close(self):
print("}", end = '')
self.r = self.r - 1
self.k = self.k - 1
def probclose(self):
return ((self.r * (self.r + self.k + 2))/(2 * self.k * (self.r + 1)))
def gen(self, n):
self.k = 2 * n
self.r = 0
while self.r != self.k:
if self.r == 0:
self.open()
elif random.uniform(0, 1) < self.probclose():
self.close()
else:
self.open()
while self.k != 0:
self.close()
print()
x = Generator()
if len(sys.argv) < 2:
print("first arg is # of parens")
sys.exit()
x.gen(int(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment