dotfiles/dotfiles/lib/python/parenthesizations.py

21 lines
536 B
Python
Raw Normal View History

2015-08-20 01:26:51 -07:00
from backports.functools_lru_cache import lru_cache
def parenthesizations(pairs):
parenthesizations = _parenthesizations(pairs * 2, net=0)
2015-08-24 15:27:29 -07:00
return parenthesizations
2015-08-20 01:26:51 -07:00
@lru_cache(maxsize=None)
def _parenthesizations(length, net=0):
if net == length:
return [')' * length]
res = prepend('(', _parenthesizations(length-1, net=net + 1))
if net > 0:
res.extend(prepend(')', _parenthesizations(length-1, net=net - 1)))
return res
def prepend(char, items):
return [char + item for item in items]