Skip to content

Instantly share code, notes, and snippets.

@gigamonkey
Created February 25, 2019 01:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gigamonkey/62769c1b495dd875470e1c2c409cf7f3 to your computer and use it in GitHub Desktop.
Save gigamonkey/62769c1b495dd875470e1c2c409cf7f3 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"Generate all strings containing just ( and ) with parens balenced."
from itertools import count
def parens():
def nested(x):
return ("(" * x) + (")" * x) if x > 0 else ""
def n_parens(n):
yield nested(n)
yield from (nested(i) + p for i in range(1, n) for p in n_parens(n - i))
return (x for n in count() for x in n_parens(n))
if __name__ == "__main__":
for i, p in enumerate(parens()):
print(p)
if i > 100:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment