🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of pfertyk

pfertyk's solution

to Say in the Python Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Given a number from 0 to 999,999,999,999, spell out that number in English.

Step 1

Handle the basic case of 0 through 99.

If the input to the program is 22, then the output should be 'twenty-two'.

Your program should complain loudly if given a number outside the blessed range.

Some good test cases for this program are:

  • 0
  • 14
  • 50
  • 98
  • -1
  • 100

Extension

If you're on a Mac, shell out to Mac OS X's say program to talk out loud.

Step 2

Implement breaking a number up into chunks of thousands.

So 1234567890 should yield a list like 1, 234, 567, and 890, while the far simpler 1000 should yield just 1 and 0.

The program must also report any values that are out of range.

Step 3

Now handle inserting the appropriate scale word between those chunks.

So 1234567890 should yield '1 billion 234 million 567 thousand 890'

The program must also report any values that are out of range. It's fine to stop at "trillion".

Step 4

Put it all together to get nothing but plain English.

12345 should give twelve thousand three hundred forty-five.

The program must also report any values that are out of range.

Extensions

Use and (correctly) when spelling out the number in English:

  • 14 becomes "fourteen".
  • 100 becomes "one hundred".
  • 120 becomes "one hundred and twenty".
  • 1002 becomes "one thousand and two".
  • 1323 becomes "one thousand three hundred and twenty-three".

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test say_test.py
  • Python 3.4+: pytest say_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest say_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/say directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see the help page.

Source

A variation on JavaRanch CattleDrive, exercise 4a http://www.javaranch.com/say.jsp

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

say_test.py

import unittest

from say import say


# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0

class SayTest(unittest.TestCase):
    def test_zero(self):
        self.assertEqual(say(0), "zero")

    def test_one(self):
        self.assertEqual(say(1), "one")

    def test_fourteen(self):
        self.assertEqual(say(14), "fourteen")

    def test_twenty(self):
        self.assertEqual(say(20), "twenty")

    def test_twenty_two(self):
        self.assertEqual(say(22), "twenty-two")

    def test_one_hundred(self):
        self.assertEqual(say(100), "one hundred")

    # additional track specific test
    def test_one_hundred_twenty(self):
        self.assertEqual(say(120), "one hundred and twenty")

    def test_one_hundred_twenty_three(self):
        self.assertEqual(say(123), "one hundred and twenty-three")

    def test_one_thousand(self):
        self.assertEqual(say(1000), "one thousand")

    def test_one_thousand_two_hundred_thirty_four(self):
        self.assertEqual(say(1234), "one thousand two hundred and thirty-four")

    # additional track specific test
    def test_eight_hundred_and_ten_thousand(self):
        self.assertEqual(say(810000), "eight hundred and ten thousand")

    def test_one_million(self):
        self.assertEqual(say(1e6), "one million")

    # additional track specific test
    def test_one_million_two(self):
        self.assertEqual(say(1000002), "one million and two")

    def test_1002345(self):
        self.assertEqual(
            say(1002345),
            "one million two thousand three hundred and forty-five")

    def test_one_billion(self):
        self.assertEqual(say(1e9), "one billion")

    def test_987654321123(self):
        self.assertEqual(
            say(987654321123), ("nine hundred and eighty-seven billion "
                                "six hundred and fifty-four million "
                                "three hundred and twenty-one thousand "
                                "one hundred and twenty-three"))

    def test_number_too_large(self):
        with self.assertRaisesWithMessage(ValueError):
            say(1e12)

    def test_number_negative(self):
        with self.assertRaisesWithMessage(ValueError):
            say(-1)

    # Utility functions
    def setUp(self):
        try:
            self.assertRaisesRegex
        except AttributeError:
            self.assertRaisesRegex = self.assertRaisesRegexp

    def assertRaisesWithMessage(self, exception):
        return self.assertRaisesRegex(exception, r".+")


if __name__ == '__main__':
    unittest.main()
MULTIPLES_OF_10 = [
    '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
    'eighty', 'ninety'
]

POWERS_OF_1000 = ['billion', 'million', 'thousand', '']

NUMBERS_BELOW_20 = [
    '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
    'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'sixteen',
    'seventeen', 'eighteen', 'nineteen'
]


def say(number):
    if not 0 <= number < 1e12:
        raise AttributeError('Given number is outside the blessed range')

    if not number:
        return 'zero'

    words = []
    for power, chunk in zip(POWERS_OF_1000, chunks_of_thousands(number)):
        if chunk:
            if words and chunk < 100 and not power:
                words.append('and')
            words.append(say_below_1000(chunk))
            if power:
                words.append(power)

    return ' '.join(words)


def chunks_of_thousands(number):
    for power in (9, 6, 3, 0):
        n, _ = divmod(number, 10**power)
        yield n % 1000


def say_below_1000(number):
    words = []
    hundreds, number_below_100 = divmod(int(number), 100)

    if hundreds:
        words.append(NUMBERS_BELOW_20[hundreds] + ' hundred')

    if 0 < number_below_100 < 20:
        words.append(NUMBERS_BELOW_20[number_below_100])
    elif number_below_100:
        tens, ones = divmod(number_below_100, 10)
        words.append(MULTIPLES_OF_10[tens])
        if ones:
            words[-1] += '-' + NUMBERS_BELOW_20[ones]

    return ' and '.join(words)

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?