From feb3ed312946b80dd5e075bc0b4792cab0c2fa93 Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Wed, 10 Feb 2016 06:30:36 -0500 Subject: [PATCH] Polish add reverse solution. --- .../add_reverse/add_reverse_solution.ipynb | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/linked_lists/add_reverse/add_reverse_solution.ipynb b/linked_lists/add_reverse/add_reverse_solution.ipynb index f3f185f..1d47753 100644 --- a/linked_lists/add_reverse/add_reverse_solution.ipynb +++ b/linked_lists/add_reverse/add_reverse_solution.ipynb @@ -73,7 +73,7 @@ "* Recursive case:\n", " * Set `value` to `carry`\n", " * Add both nodes' `data` to `value`\n", - " * Set the `new_carry` to 1 if `value >= 10, else 0`\n", + " * Set the `carry` to 1 if `value >= 10, else 0`\n", " * Set the `remainder` to `value % 10`\n", " * Create a `node` with the `remainder`\n", " * Set `node.next` to a recursive call on the `next` nodes, passing in the `carry`\n", @@ -117,31 +117,29 @@ "source": [ "class MyLinkedList(LinkedList):\n", "\n", - " def __add_reverse__(self, first_node, second_node, carry):\n", - " if type(carry) != int and carry < 0:\n", - " raise ValueError('Invalid int argument: carry')\n", - "\n", + " def _add_reverse(self, first_node, second_node, carry):\n", " # Base case\n", - " if first_node is None and second_node is None and carry == 0:\n", + " if first_node is None and second_node is None and not carry:\n", " return None\n", "\n", " # Recursive case\n", " value = carry\n", " value += first_node.data if first_node is not None else 0\n", " value += second_node.data if second_node is not None else 0\n", - " new_carry = 1 if value >= 10 else 0\n", - " remainder = value % 10\n", - " node = Node(remainder)\n", - " node.next = self.__add_reverse__(\n", + " carry = 1 if value >= 10 else 0\n", + " value %= 10\n", + " node = Node(value)\n", + " node.next = self._add_reverse(\n", " first_node.next if first_node is not None else None,\n", " second_node.next if first_node is not None else None,\n", - " new_carry)\n", + " carry)\n", " return node\n", "\n", " def add_reverse(self, first_list, second_list):\n", + " # See constraints\n", " if first_list is None or second_list is None:\n", " return None\n", - " head = self.__add_reverse__(first_list.head, second_list.head, 0)\n", + " head = self._add_reverse(first_list.head, second_list.head, 0)\n", " return MyLinkedList(head)" ] }, @@ -244,21 +242,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.10" + "pygments_lexer": "ipython3", + "version": "3.4.3" } }, "nbformat": 4,