From a5ddc4f63c94e62d1b95ebe1d5ab556021214c37 Mon Sep 17 00:00:00 2001 From: Ivan Malison Date: Thu, 20 Aug 2015 01:26:51 -0700 Subject: [PATCH] valid parenthesizations --- dotfiles/lib/python/parenthesizations.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 dotfiles/lib/python/parenthesizations.py diff --git a/dotfiles/lib/python/parenthesizations.py b/dotfiles/lib/python/parenthesizations.py new file mode 100644 index 00000000..af338799 --- /dev/null +++ b/dotfiles/lib/python/parenthesizations.py @@ -0,0 +1,22 @@ +from backports.functools_lru_cache import lru_cache + + +def parenthesizations(pairs): + parenthesizations = _parenthesizations(pairs * 2, net=0) + return call_count, parenthesizations + + +@lru_cache(maxsize=None) +def _parenthesizations(length, net=0): + if net > length or net < 0: + raise Exception() + 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]