From 9f8b760e32eea90b5722159a575894c4a3a9fdec Mon Sep 17 00:00:00 2001 From: Julien Wilson Date: Sun, 18 Dec 2016 08:29:25 -0800 Subject: [PATCH 1/4] proper parenthetics with tests, stack, linked list --- ...inary_list_to_number.cpython-27-PYTEST.pyc | Bin 1729 -> 1711 bytes ...itives_sum_negatives.cpython-27-PYTEST.pyc | Bin 1974 -> 1956 bytes .../test_digitize.cpython-27-PYTEST.pyc | Bin 1623 -> 1605 bytes .../test_fake_bin.cpython-27-PYTEST.pyc | Bin 1784 -> 1766 bytes .../test_flatten_me.cpython-27-PYTEST.pyc | Bin 1782 -> 1764 bytes .../test_last.cpython-27-PYTEST.pyc | Bin 1635 -> 1617 bytes .../test_multiples.cpython-27-PYTEST.pyc | Bin 1822 -> 1804 bytes ...t_reverse_and_mirror.cpython-27-PYTEST.pyc | Bin 1766 -> 1748 bytes .../test_sea_sick.cpython-27-PYTEST.pyc | Bin 1695 -> 1677 bytes ...test_string_to_array.cpython-27-PYTEST.pyc | Bin 1851 -> 1833 bytes .../test_sum.cpython-27-PYTEST.pyc | Bin 1905 -> 1887 bytes ...test_sum_from_string.cpython-27-PYTEST.pyc | Bin 1753 -> 1735 bytes src/binary_list_to_number.pyc | Bin 690 -> 672 bytes src/count_positives_sum_negatives.pyc | Bin 813 -> 795 bytes src/digitize.pyc | Bin 629 -> 611 bytes src/fake_bin.pyc | Bin 675 -> 657 bytes src/flatten_me.pyc | Bin 632 -> 614 bytes src/last.pyc | Bin 613 -> 595 bytes src/linked_list.py | 83 ++++++++++++++++++ src/multiples.pyc | Bin 642 -> 624 bytes src/proper_parenthetics.py | 19 ++++ src/reverse_and_mirror.pyc | Bin 754 -> 736 bytes src/sea_sick.pyc | Bin 632 -> 614 bytes src/stack.py | 24 +++++ src/string_to_array.pyc | Bin 536 -> 518 bytes src/sum_from_string.pyc | Bin 726 -> 708 bytes src/test_proper_parenthetics.py | 21 +++++ 27 files changed, 147 insertions(+) create mode 100644 src/linked_list.py create mode 100644 src/proper_parenthetics.py create mode 100644 src/stack.py create mode 100644 src/test_proper_parenthetics.py diff --git a/src/__pycache__/test_binary_list_to_number.cpython-27-PYTEST.pyc b/src/__pycache__/test_binary_list_to_number.cpython-27-PYTEST.pyc index 15650ed3a508f96b77ca029d53ae7667b946269c..21ab5d092712df945fa4dc2445d57353ce851d3e 100644 GIT binary patch delta 121 zcmX@eyPlVw`78NF8H(x|N*Eck*cfVYGI?3)+`7#Nxv8H(x|N*Eck*cfUUCZA+f7hnPlZi5LjZDKNK zlm@C`V8|9VsUZ2f$8S&tO|^% OLX*FJcr Kv0TLvbpZg;NFlrc diff --git a/src/__pycache__/test_fake_bin.cpython-27-PYTEST.pyc b/src/__pycache__/test_fake_bin.cpython-27-PYTEST.pyc index 88d45bb97fada35578da0a2019ef9a705ddad5f9..d663fdee405fb9bdd6a99bdd9dd868bba9d41d20 100644 GIT binary patch delta 122 zcmeyt`;3>J`7>5l0ObpG83`O+}C5#MNYz#F_lkJ(*1sK4B+hBqWo6DGF z8Kr}`7#J8zn1Mt=r2$Yq14AB^XSjJCvnwMb&*U#G5sY4weOdJc{=yQ$7(BU0!(1RZ7@Nm&5=xs zjM6|Q3=DZC%s{fB(lCe}NJBXWo2N3nGBR>ZzReQB7&`jaUObpG83`O+}C5#MNYz#F_lV>uj3ow8Mx4{G%HeX;= zV3ZDGVPIe=VFnTfl?Fid3=DZtp5bP0W>-c=w#k7k5sYq=-?Hj&e#FAX2w_fs#3DV} HflV0z{v91z delta 138 zcmcb}^O%R7`7hhc&&lbwKq zOklxZFhQotl|Vs8u%IC$R6FD54NRttRwYaf3=GAFCCosopwci1NHIV;1`s)8DAyRm zHG*=DCd;$D;bsIX4`KrmER)4pBN;;`7qIHH=Oh*v#~YYVp3C|RLquuvb2e1~6uL0P diff --git a/src/__pycache__/test_reverse_and_mirror.cpython-27-PYTEST.pyc b/src/__pycache__/test_reverse_and_mirror.cpython-27-PYTEST.pyc index 05ffc7464732a9359ef695d5736f76441516cfa0..d3d7d64a10a04a30bdf08ca09ecde642ded3357e 100644 GIT binary patch delta 122 zcmaFHdxe*s`7@OGvm>HTG8Hzd?N*Eck*cfVVFnTfl?EjsPO%}BYdHBh^KV9$$%k2D8AB#3vg%Ks!=^d8iS;3z=LG;& C`5z+y delta 139 zcmcb@`;3>J`7@OGv7#Nxv8Hzd?N*Eck*cfUUCjVzt7hnbp9)JllZ#H8p zWt1slVqjn>HY{NVQU#TUK_D)aV=(zR^KVAx$%k2D8Dl3avg)(vBo-IP8<=kPW94B) O6`JhFsy%r#n<4;eq$14# diff --git a/src/__pycache__/test_sea_sick.cpython-27-PYTEST.pyc b/src/__pycache__/test_sea_sick.cpython-27-PYTEST.pyc index c775ca459388dcf0e9b799bf3027c89ba473e188..f0292be4f9b16483c37129faa446fb03609220c7 100644 GIT binary patch delta 122 zcmbQw+sn(&{F#@_ZA;ij_VbJaObpG83`O+}C5#MNYz#F_lb#%--v*agNu&Dz8 Dq}v-= delta 138 zcmeC>ozKh8{F#?)YOwc4_VbJa3=GYT3`O+}C5#MNYz#FFlb>f-4ObpG83`O+}C5#MNYz#F_ljE7x1sK4B+hBqWo2M~p zGfD^XF)%QcFawE#N&}#J28KK+&v5e{W>-c=fyqj&5sZP8t6B9oZ)Rm;gfJ&>W>uRk H!mbVgsyZ9i delta 138 zcmZ3>f-43=GYT3`O+}C5#MNYz#FFljE7x1(?8s+hBrBo2M~p zGfD%MFfinmFaybgO2Z&NAPwahY`(+n%E-t+S&21*F>3N!HhuP-#Ny(31JlX3*fb_z KV7-GO>JI>w^dk=d diff --git a/src/__pycache__/test_sum.cpython-27-PYTEST.pyc b/src/__pycache__/test_sum.cpython-27-PYTEST.pyc index 7a0308daad50a8c66705e7b3358d65e6fb888ded..1b14d6b6d8d322ae127c26d6b87421aab06adb2a 100644 GIT binary patch delta 40 pcmey!cb|`)`7}y#WT_=BI)1R!zE;X5*?H!!w3;-N~4L$$> delta 56 xcmcc5_mPjC`7}y#W{U*O<(`U~~EG~{WFr6&LE;IQb>pKilR{%Q96Gs35 diff --git a/src/__pycache__/test_sum_from_string.cpython-27-PYTEST.pyc b/src/__pycache__/test_sum_from_string.cpython-27-PYTEST.pyc index ab6449a458c2cc9980280d1a4fd6476979244c34..72c1e508fcddf06eb6c98389b618a08bb6a4bb7e 100644 GIT binary patch delta 123 zcmcb~dz_b@`78NF8H(x|N*Eck*cfVWn^TUe1Ii_F>taZtN!LdRwhOWb8;Z7+T=}a F>HrVA92@`u delta 138 zcmX@kdy|))`710mn?8F^VsUZ2f$8K5HjT-7 JtamU({Q>9tA};^{ diff --git a/src/binary_list_to_number.pyc b/src/binary_list_to_number.pyc index 65ecd78ec709eb3cae81cd9a6342e50275eae73a..676595a51950650629ba89989e6d98c124d93163 100644 GIT binary patch delta 40 pcmdnQx`36P`7FV2008yK5qHk*x|`7~|O$qb9Fs(w{8DGzreqpDe~K4gdq~3(x=n delta 56 xcmbQuww8^Z`7~|O$lP51@(r3>}EG~{WFr6&OGzCM%a54+CH~{zS5TyVB diff --git a/src/digitize.pyc b/src/digitize.pyc index 55704381c3bcf950d56c5976b1d9a7090f52915e..ff345345c321b4875028f39962063e0610fff00f 100644 GIT binary patch delta 40 pcmey$@|cC4`7{A&TT_?|F)Sq0$BscjpqZ^!O2mt<=3}*lU delta 56 xcmbQpx|o%n`7{A&T{U#eS>9gk~78l1Gm`;vkQkeXT(G5e?7y#VU5RCu; diff --git a/src/flatten_me.pyc b/src/flatten_me.pyc index 74e88661aed65e93c6969dac4caf3d73a729bd5f..3bf2f48b871a50f625f618d70a1e470e98d0e021 100644 GIT binary patch delta 40 pcmeyt@{EO@`7`9D_?vr_$^d~Q3%!0FICMPn90{{Vm3zq-@ delta 56 xcmaFH@`Ht)`7`9D_0h6;B_1SY0i;Lq8OeY&M$xYtM=!YR{3IO>z5aR#< diff --git a/src/last.pyc b/src/last.pyc index d32bfa8d19b30881f25dfd5ab2b3eed7e6edfd10..1cf76972aff9ff7a56add38062105b167307549a 100644 GIT binary patch delta 34 lcmaFLa+!sl`74P`jZ2gq$gisbcged0Q@xz-T(jq delta 56 xcmeys(!|Qn{F#@_E!KM@dnqHM|73n9efFHh;^KG%)5$hWvXhT9x?_l%006+G4}$;z diff --git a/src/proper_parenthetics.py b/src/proper_parenthetics.py new file mode 100644 index 0000000..8e19135 --- /dev/null +++ b/src/proper_parenthetics.py @@ -0,0 +1,19 @@ +"""Ensure the same number of opening and closing parenthetics in a string.""" + +from stack import Stack + + +def proper_parenthetics(input_string): + """Ensure the balance of opening and closing parenthtics.""" + parenthetics_stack = Stack() + for i in input_string: + if i == '(': + parenthetics_stack.push(i) + if i == ')': + if parenthetics_stack.head_node is None: + return -1 + else: + parenthetics_stack.pop() + if parenthetics_stack.head_node is None: + return 0 + return 1 diff --git a/src/reverse_and_mirror.pyc b/src/reverse_and_mirror.pyc index 99b801a2cc990c555b4547c1d4f39702e50ff5a2..c21cbb1d6e49430f46bc58d564e6805525578085 100644 GIT binary patch delta 40 pcmeyw`hb<4`79gk~78l1Gm`?uBScV~@Hu)rzH~=es6HNdB diff --git a/src/sea_sick.pyc b/src/sea_sick.pyc index 25b92c72a54119ebe45ec1e01b213ee05e93c8e3..a146356f6fed50b6715d35f341759fc8e0ebde5e 100644 GIT binary patch delta 40 pcmeyt@{EO@`7{*PAu9Nwh^e3-kOo6lHCZ{q90{{ZS3#$MC delta 56 xcmaFH@`Ht)`7{*PAev{dl^x1O~i;Lq8OefE0Ov4aSm>kR`3;^aw5NH4Z diff --git a/src/stack.py b/src/stack.py new file mode 100644 index 0000000..7c6e988 --- /dev/null +++ b/src/stack.py @@ -0,0 +1,24 @@ +"""Implementation of Stack data type.""" + +from linked_list import LinkedList + + +class Stack(object): + """Class representation of a stack.""" + + def __init__(self, iterable=None): + """Instantiate stack.""" + self.linked_list = LinkedList(iterable) + self.length = self.linked_list.length + self.head_node = self.linked_list.head_node + + def push(self, contents): + """Add node to this stack.""" + self.linked_list.push(contents) + self.head_node = self.linked_list.head_node + + def pop(self): + """Remove and return the current head node.""" + old_head_node_value = self.linked_list.pop() + self.head_node = self.linked_list.head_node + return old_head_node_value diff --git a/src/string_to_array.pyc b/src/string_to_array.pyc index fd388680651a0be1359658142197193128f28e97..8dccd6889a6ba70f27fac6ad05900e1af967f4ef 100644 GIT binary patch delta 39 ocmbQi(#FEh{F#@_ZA;ih_P>lilUFe6Pkz9tI602d6V9^$001@(3;+NC delta 55 wcmZo;nZd%&{F#?)mXr5H_P>mwljk$)v*#oh7snfzPCmn^JUNun6GPMr0O^GhvH$=8 diff --git a/src/sum_from_string.pyc b/src/sum_from_string.pyc index c3fa60c6741552e7f16aaaffe4a265ceda3cc167..6fa762d50db28d58324d14085a090aa1a7f3b02f 100644 GIT binary patch delta 40 pcmcb{dW4mo`79gk~78l1Gm`;AcSc4&=Jb5jXH~ Date: Tue, 27 Dec 2016 23:24:43 -0800 Subject: [PATCH 2/4] sort cards with and without prioQ. and tests --- setup.py | 3 +- src/code_katas.egg-info/SOURCES.txt | 2 + src/code_katas.egg-info/top_level.txt | 2 + src/priority.py | 40 ++++++++++++++++ src/proper_parenthetics.py | 3 +- src/sort_cards.py | 49 +++++++++++++++++++ src/test_priority.py | 69 +++++++++++++++++++++++++++ src/test_sort_cards.py | 26 ++++++++++ 8 files changed, 191 insertions(+), 3 deletions(-) create mode 100644 src/priority.py create mode 100644 src/sort_cards.py create mode 100644 src/test_priority.py create mode 100644 src/test_sort_cards.py diff --git a/setup.py b/setup.py index cd6801e..b669148 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,8 @@ py_modules=["last", "string_to_array", "fake_binary", "count_positives_sum_negatives", "digitize", "binary_list_to_number", "sea_sick", "reverse_and_mirror", - "flatten_me", "sum_from_string", "multiples"], + "flatten_me", "sum_from_string", "multiples", "sort_cards", + "priority"], install_requires=[], extras_require={ "test": ["pytest", "pytest-watch", "pytest-cov", "tox"] diff --git a/src/code_katas.egg-info/SOURCES.txt b/src/code_katas.egg-info/SOURCES.txt index c18a04c..81c3bbc 100644 --- a/src/code_katas.egg-info/SOURCES.txt +++ b/src/code_katas.egg-info/SOURCES.txt @@ -5,8 +5,10 @@ src/digitize.py src/flatten_me.py src/last.py src/multiples.py +src/priority.py src/reverse_and_mirror.py src/sea_sick.py +src/sort_cards.py src/string_to_array.py src/sum_from_string.py src/code_katas.egg-info/PKG-INFO diff --git a/src/code_katas.egg-info/top_level.txt b/src/code_katas.egg-info/top_level.txt index 4429a32..2b582bf 100644 --- a/src/code_katas.egg-info/top_level.txt +++ b/src/code_katas.egg-info/top_level.txt @@ -5,7 +5,9 @@ fake_binary flatten_me last multiples +priority reverse_and_mirror sea_sick +sort_cards string_to_array sum_from_string diff --git a/src/priority.py b/src/priority.py new file mode 100644 index 0000000..10d6cae --- /dev/null +++ b/src/priority.py @@ -0,0 +1,40 @@ +"""Priority Queue data structure.""" + + +class PriorityQueue(object): + """Priority Queue data structure. + + .insert(item) - adds an item to the queue and sorts + .pop() - removes the highest priority item, returns its value. + .peek() - returns the value of the highest priority item. + """ + + def __init__(self, iterable=None): + """Initialize the Priority Queue.""" + self._pq_dict = {} + if hasattr(iterable, "__iter__"): + for val in iterable: + self.insert(val[1], priority=val[0]) + + def insert(self, value, priority=0): + """Insert values and priorities in to priority queue.""" + if priority not in self._pq_dict.keys(): + self._pq_dict[priority] = [] + self._pq_dict[priority].append(value) + + def pop(self): + """Remove the highest priority item, returns its value.""" + pop_val = self.peek() + hi_pri = sorted(self._pq_dict.keys())[0] + if len(self._pq_dict[hi_pri]) == 1: + del self._pq_dict[hi_pri] + else: + self._pq_dict[hi_pri] = self._pq_dict[hi_pri][1:] + return pop_val + + def peek(self): + if len(self._pq_dict.keys()) == 0: + raise KeyError("The Priority Queue is empty.") + hi_pri = sorted(self._pq_dict.keys())[0] + pop_val = self._pq_dict[hi_pri][0] + return pop_val diff --git a/src/proper_parenthetics.py b/src/proper_parenthetics.py index 8e19135..aaeff61 100644 --- a/src/proper_parenthetics.py +++ b/src/proper_parenthetics.py @@ -12,8 +12,7 @@ def proper_parenthetics(input_string): if i == ')': if parenthetics_stack.head_node is None: return -1 - else: - parenthetics_stack.pop() + parenthetics_stack.pop() if parenthetics_stack.head_node is None: return 0 return 1 diff --git a/src/sort_cards.py b/src/sort_cards.py new file mode 100644 index 0000000..de248f8 --- /dev/null +++ b/src/sort_cards.py @@ -0,0 +1,49 @@ +"""Sort a deck of cards code-kata using a Priority Queue.""" + +from priority import PriorityQueue + +card_dict = { + 'A': 1, + 'T': 10, + 'J': 11, + 'Q': 12, + 'K': 13, + 1: 'A', + 10: 'T', + 11: 'J', + 12: 'Q', + 13: 'K', +} + + +def sort_cards(cards): + """Sort shuffled list of cards, sorted by rank.""" + card_list = [] + for card in cards: + try: + card_list.append(int(card)) + except ValueError: + card_list.append(card_dict[card]) + card_list.sort() + result = [] + for card in card_list: + if card > 1 and card < 10: + result.append(str(card)) + else: + result.append(card_dict[card]) + return result + + +def sort_cards_w_pq(cards): + """Sort shuffled list of cards, sorted by rank, using a priority queue.""" + card_list = [] + for card in cards: + try: + card_list.append((int(card), card)) + except ValueError: + card_list.append(card_dict[card]) + card_q = PriorityQueue(card_list) + result = [] + for i in range(len(card_list)): + result.append(card_q.pop()) + return result diff --git a/src/test_priority.py b/src/test_priority.py new file mode 100644 index 0000000..78b30a7 --- /dev/null +++ b/src/test_priority.py @@ -0,0 +1,69 @@ +"""Test the priority queue's functionality.""" + + +import pytest + +INPUT_VALUES = [ + ([], {}, None, None), + ([(1, 'a'), (2, 'b'), (3, 'c')], {1: ['a'], 2: ['b'], 3: ['c']}, 'a', 1), + ([(2, 'a'), (5, 'b'), (12, 'c')], {2: ['a'], 5: ['b'], 12: ['c']}, 'a', 2), + ([(15, 'words'), (6, 'are'), (70, 'hard')], {6: ['are'], 15: ['words'], 70: ['hard']}, 'are', 6), + ([(1, 15), (2, 20), (3, 25)], {1: [15], 2: [20], 3: [25]}, 15, 1), + ([(1, 'a'), (1, 'b'), (2, 'c')], {1: ['a', 'b'], 2: ['c']}, 'a', 1), +] + + +@pytest.fixture(scope="module", params=INPUT_VALUES) +def pri(request): + """Paramaterized fixture for testing.""" + from priority import PriorityQueue + processed = PriorityQueue(request.param[0]) + prioq = (processed, request.param[1], request.param[2], request.param[3]) + return prioq + + +def test_init(pri): + """Test that the class initializes.""" + from priority import PriorityQueue + assert isinstance(pri[0], PriorityQueue) + + +def test_insert(pri): + """Test that values are inserted at the right priority in the right order.""" + assert pri[0]._pq_dict == pri[1] + # (the_input, the_expected_output) = pri + + +def test_pop(pri): + """Test that pop returns the right value.""" + try: + assert pri[0].pop() == pri[2] + except KeyError: + assert True + + +def test_del(pri): + """Test that empty keys are deleted.""" + try: + pri[0].pop() + pri[0].pop() + assert pri[3] not in pri[0]._pq_dict + except KeyError: + assert True + + +def test_pop_remove(pri): + """Test that pop properly removes values.""" + try: + pri[0].pop() + assert pri[2] not in pri[0]._pq_dict[pri[3]] + except KeyError: + assert True + + +def test_peek(pri): + """Test that peek returns the right value.""" + try: + assert pri[0].peek() == pri[2] + except KeyError: + assert True diff --git a/src/test_sort_cards.py b/src/test_sort_cards.py new file mode 100644 index 0000000..6517f2a --- /dev/null +++ b/src/test_sort_cards.py @@ -0,0 +1,26 @@ +"""Tests for count_positives_sum_negatives.count_positives_sum_negatives.""" +import pytest + + +ASSERTIONS = [ + [list('39A5T824Q7J6K'), list('A23456789TJQK')], + [list('Q286JK395A47T'), list('A23456789TJQK')], + [list('54TQKJ69327A8'), list('A23456789TJQK')], + [list('AAA4555336773'), list('AAA3334555677')], + [list('3'), list('3')], + [list('TTTTTTTTTTTAK'), list('ATTTTTTTTTTTK')], +] + + +@pytest.mark.parametrize("n, result", ASSERTIONS) +def test_sort_cards(n, result): + """Test sort_cards() for proper output in test cases.""" + from sort_cards import sort_cards + assert sort_cards(n) == result + + +@pytest.mark.parametrize("n, result", ASSERTIONS) +def test_sort_cards_w_pq(n, result): + """Test sort_cards_w_pq() for proper output in test cases.""" + from sort_cards import sort_cards + assert sort_cards(n) == result From 77add21bd327152e169933071114320dd7ca6f95 Mon Sep 17 00:00:00 2001 From: Julien Wilson Date: Tue, 27 Dec 2016 23:29:00 -0800 Subject: [PATCH 3/4] Update README.md --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index 18aaf11..a58cf21 100644 --- a/README.md +++ b/README.md @@ -130,3 +130,23 @@ def multiples(s1, s2, s3): return [a for a in xrange(1, s3) if not(a % s1 or a % s2)] ``` +Sum of the first nth terms of a series (7 kyu) +- Module: series_sum.py +- Tests: test_series_sum.py +- Link: http://www.codewars.com/kata/sum-of-the-first-nth-term-of-series/train/python +- Interesting Solution: Making the numerator a float() was smart. +```python +def series_sum(n): + """Solution by MMMAAANNN""" + return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n))) +``` + + +Proper Parenthetics +- Module: proper_parenthetics.py +- Tests: test_proper_parenthetics.py + + +Sort Cards (7kyu) +-Module: sort_cards.py +-Tests: test_sort_cards.py From 290ad3750c65ce2b8bee76993f34bd4a0234c0fe Mon Sep 17 00:00:00 2001 From: Julien Wilson Date: Tue, 27 Dec 2016 23:29:36 -0800 Subject: [PATCH 4/4] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a58cf21..aaaa060 100644 --- a/README.md +++ b/README.md @@ -150,3 +150,4 @@ Proper Parenthetics Sort Cards (7kyu) -Module: sort_cards.py -Tests: test_sort_cards.py +-Link: https://www.codewars.com/kata/sort-deck-of-cards/train/python