{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Solution Notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem: Given an int, repeatedly add its digits until the result is one digit.\n", "\n", "* [Constraints](#Constraints)\n", "* [Test Cases](#Test-Cases)\n", "* [Algorithm](#Algorithm)\n", "* [Code](#Code)\n", "* [Unit Test](#Unit-Test)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Constraints\n", "\n", "* Can we assume num is not negative?\n", " * Yes\n", "* Can we assume the inputs are valid?\n", " * No\n", "* Can we assume this fits memory?\n", " * Yes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test Cases\n", "\n", "
\n",
    "* None input -> TypeError\n",
    "* negative input -> ValueError\n",
    "* 9 -> 9\n",
    "* 138 -> 3\n",
    "* 65536 -> 7\n",
    "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Algorithm\n", "\n", "The naive solution simply isolates each digit with with modulo and integer division. We'll add each isolated digit to a list and sum the values.\n", "\n", "
\n",
    "138 % 10 = 8 -> isolated\n",
    "138 // 10 = 13\n",
    "13 % 10 = 3 -> isolated\n",
    "13 // 10 = 1\n",
    "1 % 10 = 1 -> isolated\n",
    "
\n", "\n", "A more optimal solution exists, by recognizing this is a digital root. See the [Wikipedia article](https://en.wikipedia.org/wiki/Digital_root) for more information.\n", "\n", "Complexity:\n", "* Time: O(1)\n", "* Space: O(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class Solution(object):\n", "\n", " def add_digits(self, num):\n", " if num is None:\n", " raise TypeError('num cannot be None')\n", " if num < 0:\n", " raise ValueError('num cannot be negative')\n", " digits = []\n", " while num != 0:\n", " digits.append(num % 10)\n", " num //= 10\n", " digits_sum = sum(digits)\n", " if digits_sum >= 10:\n", " return self.add_digits(digits_sum)\n", " else:\n", " return digits_sum\n", "\n", " def add_digits_optimized(self, num):\n", " if num is None:\n", " raise TypeError('num cannot be None')\n", " if num < 0:\n", " raise ValueError('num cannot be negative')\n", " if num == 0:\n", " return 0\n", " elif num % 9 == 0:\n", " return 9\n", " else:\n", " return num % 9" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unit Test" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting test_add_digits.py\n" ] } ], "source": [ "%%writefile test_add_digits.py\n", "import unittest\n", "\n", "\n", "class TestAddDigits(unittest.TestCase):\n", "\n", " def test_add_digits(self, func):\n", " self.assertRaises(TypeError, func, None)\n", " self.assertRaises(ValueError, func, -1)\n", " self.assertEqual(func(0), 0)\n", " self.assertEqual(func(9), 9)\n", " self.assertEqual(func(138), 3)\n", " self.assertEqual(func(65536), 7) \n", " print('Success: test_add_digits')\n", "\n", "\n", "def main():\n", " test = TestAddDigits()\n", " solution = Solution()\n", " test.test_add_digits(solution.add_digits)\n", " try:\n", " test.test_add_digits(solution.add_digits_optimized)\n", " except NameError:\n", " # Alternate solutions are only defined\n", " # in the solutions file\n", " pass\n", "\n", "\n", "if __name__ == '__main__':\n", " main()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success: test_add_digits\n", "Success: test_add_digits\n" ] } ], "source": [ "%run -i test_add_digits.py" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.2" } }, "nbformat": 4, "nbformat_minor": 1 }