Skip to content

Instantly share code, notes, and snippets.

@pepasflo
Last active November 14, 2018 16:19
Show Gist options
  • Save pepasflo/802b7ae7c0d2b3aa9fa02b86e572264a to your computer and use it in GitHub Desktop.
Save pepasflo/802b7ae7c0d2b3aa9fa02b86e572264a to your computer and use it in GitHub Desktop.
large test file generator for the "balanced parens" problem
$ for i in {1..10}; do ./gen-test-file.py 20 ; echo ; done
[{{}{[[(){}[[][[([[][()]])(())]][{}]]][{}]]}}]
{[{{}([{{({[[(({}{{}}()))]]})[{}]}}])}()]}
{[{[[{{[]}([{({(({([])}))}{[]})}]())()}]]}[]()]}
()[({({[]({[{()}{[()]}]}[])}{}()())})[]]
[[([]{}{([([[{(([{()[([])]}])[])[]}](){}(){[]}])])}[])]]
[({{[{[][({[]({[(){()[]}][]})}{}())]}]}{}})[]]
({[]{()}(((({({[]([[[]]])()})})){()}){}[])}()[])
[(){{{[((((([[{{}}({})]{}]([{}]())[])){})))]}}({}()[])}]
[{{{}}([[]([]()({}[]()))])}]
(())()({(([(){}{}[][([])]]))})
#!/usr/bin/env python
import sys
import random
def opposite(ch):
if ch == '(': return ')'
if ch == '[': return ']'
if ch == '{': return '}'
openers = ['(', '[', '{']
closers = [')', ']', '}']
output = []
stack = []
# in first half, 75% chance of push, 25% chance pop
# in second half, reverse, until pop to zero.
early = [True, True, True, False]
late = [True, False, False, False]
n = int(sys.argv[1])
for _ in xrange(n):
if random.choice(early):
ch = random.choice(openers)
output.append(ch)
stack.append(ch)
else:
if len(stack) > 0:
ch = stack.pop()
output.append(opposite(ch))
while True:
if random.choice(late):
ch = random.choice(openers)
output.append(ch)
stack.append(ch)
else:
ch = stack.pop()
output.append(opposite(ch))
if len(stack) == 0:
break
for ch in output:
sys.stdout.write(ch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment