Skip to content

Instantly share code, notes, and snippets.

@garydoranjr
Created February 11, 2011 22:03
Show Gist options
  • Save garydoranjr/823132 to your computer and use it in GitHub Desktop.
Save garydoranjr/823132 to your computer and use it in GitHub Desktop.
Prints almost matched parens
#!/usr/bin/python
from random import random
BE_EVIL = True
MAX_DEPTH = 20
PROB_t = 0.05
PROB_p = 0.4
def production(depth):
depth += 1
if depth > MAX_DEPTH or random() < PROB_t:
return terminal()
elif random() < PROB_p:
return '%s%s' % (production(depth),
production(depth))
else:
return '(%s)' % production(depth)
def terminal():
global BE_EVIL
if BE_EVIL:
BE_EVIL = False
return '('
else:
return '()'
print '(%s)' % production(0)
@garydoranjr
Copy link
Author

![http://xkcd.com/859/](http://imgs.xkcd.com/comics/(.png)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment