Rework n pairs parens challenge (#145)

This commit is contained in:
Donne Martin 2017-02-08 06:36:49 -05:00 committed by GitHub
parent 2f2e25c33d
commit a06617f0eb
4 changed files with 122 additions and 94 deletions

View File

@ -18,7 +18,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Problem: Print all valid combinations of n-pairs of parentheses.\n", "## Problem: Find all valid combinations of n-pairs of parentheses.\n",
"\n", "\n",
"* [Constraints](#Constraints)\n", "* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n", "* [Test Cases](#Test-Cases)\n",
@ -33,7 +33,17 @@
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Constraints\n", "## Constraints\n",
"* None" "\n",
"* Is the input an integer representing the number of pairs?\n",
" * Yes\n",
"* Can we assume the inputs are valid?\n",
" * No\n",
"* Is the output a list of valid combinations?\n",
" * Yes\n",
"* Should the output have duplicates?\n",
" * No\n",
"* Can we assume this fits memory?\n",
" * Yes"
] ]
}, },
{ {
@ -42,10 +52,14 @@
"source": [ "source": [
"## Test Cases\n", "## Test Cases\n",
"\n", "\n",
"<pre>\n",
"* None -> Exception\n",
"* Negative -> Exception\n",
"* 0 -> []\n", "* 0 -> []\n",
"* 1 -> [()]\n", "* 1 -> ['()']\n",
"* 2 -> [(()), ()()]\n", "* 2 -> ['(())', '()()']\n",
"* 3 -> [((())), (()()), (())(), ()(()), ()()()]" "* 3 -> ['((()))', '(()())', '(())()', '()(())', '()()()']\n",
"</pre>"
] ]
}, },
{ {
@ -72,17 +86,11 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"def parentheses_util(no_left, no_right, pair_string, result):\n", "class Parentheses(object):\n",
" # TODO: implement parentheses pairing here\n",
" pass\n",
"\n", "\n",
"\n", " def find_pair(self, num_pairs):\n",
"def pair_parentheses(n):\n", " # TODO: implement me\n",
" result_set = set()\n", " pass"
" if n == 0:\n",
" return result_set\n",
" parentheses_util(n, n, '', result_set)\n",
" return result_set"
] ]
}, },
{ {
@ -101,27 +109,30 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# %load test_n_pairs_parentheses.py\n", "# %load test_n_pairs_parentheses.py\n",
"from nose.tools import assert_equal\n", "from nose.tools import assert_equal, assert_raises\n",
"\n", "\n",
"\n", "\n",
"class TestPairParentheses(object):\n", "class TestPairParentheses(object):\n",
"\n", "\n",
" def test_pair_parentheses(self, solution):\n", " def test_pair_parentheses(self):\n",
" assert_equal(solution(0), set([]))\n", " parentheses = Parentheses()\n",
" assert_equal(solution(1), set(['()']))\n", " assert_raises(TypeError, parentheses.find_pair, None)\n",
" assert_equal(solution(2), set(['(())', \n", " assert_raises(ValueError, parentheses.find_pair, -1)\n",
" '()()']))\n", " assert_equal(parentheses.find_pair(0), [])\n",
" assert_equal(solution(3), set(['((()))', \n", " assert_equal(parentheses.find_pair(1), ['()'])\n",
" '(()())', \n", " assert_equal(parentheses.find_pair(2), ['(())',\n",
" '(())()', \n", " '()()'])\n",
" '()(())', \n", " assert_equal(parentheses.find_pair(3), ['((()))',\n",
" '()()()']))\n", " '(()())',\n",
" '(())()',\n",
" '()(())',\n",
" '()()()'])\n",
" print('Success: test_pair_parentheses')\n", " print('Success: test_pair_parentheses')\n",
"\n", "\n",
"\n", "\n",
"def main():\n", "def main():\n",
" test = TestPairParentheses()\n", " test = TestPairParentheses()\n",
" test.test_pair_parentheses(pair_parentheses)\n", " test.test_pair_parentheses()\n",
"\n", "\n",
"\n", "\n",
"if __name__ == '__main__':\n", "if __name__ == '__main__':\n",
@ -136,34 +147,25 @@
"\n", "\n",
"Review the [Solution Notebook](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/recursion_dynamic/n_pairs_parentheses/n_pairs_parentheses_solution.ipynb) for a discussion on algorithms and code solutions." "Review the [Solution Notebook](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/recursion_dynamic/n_pairs_parentheses/n_pairs_parentheses_solution.ipynb) for a discussion on algorithms and code solutions."
] ]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
} }
], ],
"metadata": { "metadata": {
"kernelspec": { "kernelspec": {
"display_name": "Python 2", "display_name": "Python 3",
"language": "python", "language": "python",
"name": "python2" "name": "python3"
}, },
"language_info": { "language_info": {
"codemirror_mode": { "codemirror_mode": {
"name": "ipython", "name": "ipython",
"version": 2 "version": 3
}, },
"file_extension": ".py", "file_extension": ".py",
"mimetype": "text/x-python", "mimetype": "text/x-python",
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython2", "pygments_lexer": "ipython3",
"version": "2.7.10" "version": "3.5.0"
} }
}, },
"nbformat": 4, "nbformat": 4,

View File

@ -18,7 +18,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Problem: Print all valid combinations of n-pairs of parentheses.\n", "## Problem: Find all valid combinations of n-pairs of parentheses.\n",
"\n", "\n",
"* [Constraints](#Constraints)\n", "* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n", "* [Test Cases](#Test-Cases)\n",
@ -32,7 +32,17 @@
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Constraints\n", "## Constraints\n",
"* None" "\n",
"* Is the input an integer representing the number of pairs?\n",
" * Yes\n",
"* Can we assume the inputs are valid?\n",
" * No\n",
"* Is the output a list of valid combinations?\n",
" * Yes\n",
"* Should the output have duplicates?\n",
" * No\n",
"* Can we assume this fits memory?\n",
" * Yes"
] ]
}, },
{ {
@ -41,10 +51,14 @@
"source": [ "source": [
"## Test Cases\n", "## Test Cases\n",
"\n", "\n",
"* 0 -> ' '\n", "<pre>\n",
"* 1 -> ()\n", "* None -> Exception\n",
"* 2 -> (()), ()()\n", "* Negative -> Exception\n",
"* 3 -> ((())), (()()), (())(), ()(()), ()()()" "* 0 -> []\n",
"* 1 -> ['()']\n",
"* 2 -> ['(())', '()()']\n",
"* 3 -> ['((()))', '(()())', '(())()', '()(())', '()()()']\n",
"</pre>"
] ]
}, },
{ {
@ -64,14 +78,14 @@
" - Add the string generated to the result set\n", " - Add the string generated to the result set\n",
"* Case 1: `l > 0`\n", "* Case 1: `l > 0`\n",
" - Add a left parenthesis to the parentheses string.\n", " - Add a left parenthesis to the parentheses string.\n",
" - Call parentheses_util(l - 1, r, new_string, result_set)\n", " - Recurse (l - 1, r, new_string, result_set)\n",
"* Case 2: `r > l`\n", "* Case 2: `r > l`\n",
" - Add a right parenthesis to the parentheses string.\n", " - Add a right parenthesis to the parentheses string.\n",
" - Call parentheses_util(l, r - 1, new_string, result_set)\n", " - Recurse (l, r - 1, new_string, result_set)\n",
"\n", "\n",
"Complexity:\n", "Complexity:\n",
"* Time: `O(4^n/n^(3/2))`. See [Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number#Applications_in_combinatorics)\n", "* Time: `O(4^n/n^(3/2))`, see [Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number#Applications_in_combinatorics) - 1, 1, 2, 5, 14, 42, 132...\n",
"* Space complexity: `O(n)` (Due to the implicit call stack storing a maximum of 2n function calls)" "* Space complexity: `O(n)`, due to the implicit call stack storing a maximum of 2n function calls)"
] ]
}, },
{ {
@ -89,22 +103,28 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"def parentheses_util(no_left, no_right, pair_string, result):\n", "class Parentheses(object):\n",
" if no_left == 0 and no_right == 0:\n", "\n",
" result.add(pair_string)\n", " def find_pair(self, num_pairs):\n",
" if num_pairs is None:\n",
" raise TypeError('num_pairs cannot be None')\n",
" if num_pairs < 0:\n",
" raise ValueError('num_pairs cannot be < 0')\n",
" if not num_pairs:\n",
" return []\n",
" results = []\n",
" curr_results = []\n",
" self._find_pair(num_pairs, num_pairs, curr_results, results)\n",
" return results\n",
"\n",
" def _find_pair(self, nleft, nright, curr_results, results):\n",
" if nleft == 0 and nright == 0:\n",
" results.append(''.join(curr_results))\n",
" else:\n", " else:\n",
" if no_left > 0:\n", " if nleft >= 0:\n",
" parentheses_util(no_left - 1, no_right, pair_string + '(', result)\n", " self._find_pair(nleft-1, nright, curr_results+['('], results)\n",
" if no_right > no_left:\n", " if nright > nleft:\n",
" parentheses_util(no_left, no_right - 1, pair_string + ')', result)\n", " self._find_pair(nleft, nright-1, curr_results+[')'], results)"
"\n",
"\n",
"def pair_parentheses(n):\n",
" result_set = set()\n",
" if n == 0:\n",
" return result_set\n",
" parentheses_util(n, n, '', result_set)\n",
" return result_set"
] ]
}, },
{ {
@ -131,27 +151,30 @@
], ],
"source": [ "source": [
"%%writefile test_n_pairs_parentheses.py\n", "%%writefile test_n_pairs_parentheses.py\n",
"from nose.tools import assert_equal\n", "from nose.tools import assert_equal, assert_raises\n",
"\n", "\n",
"\n", "\n",
"class TestPairParentheses(object):\n", "class TestPairParentheses(object):\n",
"\n", "\n",
" def test_pair_parentheses(self, solution):\n", " def test_pair_parentheses(self):\n",
" assert_equal(solution(0), set([]))\n", " parentheses = Parentheses()\n",
" assert_equal(solution(1), set(['()']))\n", " assert_raises(TypeError, parentheses.find_pair, None)\n",
" assert_equal(solution(2), set(['(())', \n", " assert_raises(ValueError, parentheses.find_pair, -1)\n",
" '()()']))\n", " assert_equal(parentheses.find_pair(0), [])\n",
" assert_equal(solution(3), set(['((()))', \n", " assert_equal(parentheses.find_pair(1), ['()'])\n",
" '(()())', \n", " assert_equal(parentheses.find_pair(2), ['(())',\n",
" '(())()', \n", " '()()'])\n",
" '()(())', \n", " assert_equal(parentheses.find_pair(3), ['((()))',\n",
" '()()()']))\n", " '(()())',\n",
" '(())()',\n",
" '()(())',\n",
" '()()()'])\n",
" print('Success: test_pair_parentheses')\n", " print('Success: test_pair_parentheses')\n",
"\n", "\n",
"\n", "\n",
"def main():\n", "def main():\n",
" test = TestPairParentheses()\n", " test = TestPairParentheses()\n",
" test.test_pair_parentheses(pair_parentheses)\n", " test.test_pair_parentheses()\n",
"\n", "\n",
"\n", "\n",
"if __name__ == '__main__':\n", "if __name__ == '__main__':\n",
@ -180,21 +203,21 @@
], ],
"metadata": { "metadata": {
"kernelspec": { "kernelspec": {
"display_name": "Python 2", "display_name": "Python 3",
"language": "python", "language": "python",
"name": "python2" "name": "python3"
}, },
"language_info": { "language_info": {
"codemirror_mode": { "codemirror_mode": {
"name": "ipython", "name": "ipython",
"version": 2 "version": 3
}, },
"file_extension": ".py", "file_extension": ".py",
"mimetype": "text/x-python", "mimetype": "text/x-python",
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython2", "pygments_lexer": "ipython3",
"version": "2.7.10" "version": "3.5.0"
} }
}, },
"nbformat": 4, "nbformat": 4,

View File

@ -1,24 +1,27 @@
from nose.tools import assert_equal from nose.tools import assert_equal, assert_raises
class TestPairParentheses(object): class TestPairParentheses(object):
def test_pair_parentheses(self, solution): def test_pair_parentheses(self):
assert_equal(solution(0), set([])) parentheses = Parentheses()
assert_equal(solution(1), set(['()'])) assert_raises(TypeError, parentheses.find_pair, None)
assert_equal(solution(2), set(['(())', assert_raises(ValueError, parentheses.find_pair, -1)
'()()'])) assert_equal(parentheses.find_pair(0), [])
assert_equal(solution(3), set(['((()))', assert_equal(parentheses.find_pair(1), ['()'])
assert_equal(parentheses.find_pair(2), ['(())',
'()()'])
assert_equal(parentheses.find_pair(3), ['((()))',
'(()())', '(()())',
'(())()', '(())()',
'()(())', '()(())',
'()()()'])) '()()()'])
print('Success: test_pair_parentheses') print('Success: test_pair_parentheses')
def main(): def main():
test = TestPairParentheses() test = TestPairParentheses()
test.test_pair_parentheses(pair_parentheses) test.test_pair_parentheses()
if __name__ == '__main__': if __name__ == '__main__':