Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Say in the Python Track

Published at Jul 13 2018 · 0 comments
Test suite


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


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.


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.


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.


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):
            "one million two thousand three hundred and forty-five")

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

    def test_987654321123(self):
            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):

    def test_number_negative(self):
        with self.assertRaisesWithMessage(ValueError):

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

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

if __name__ == '__main__':
class Say:

    VALS = {
        1000000000: 'billion',
        1000000: 'million',
        1000: 'thousand',
        90: 'ninety',
        80: 'eighty',
        70: 'seventy',
        60: 'sixty',
        50: 'fifty',
        40: 'forty',
        30: 'thirty',
        20: 'twenty',
        19: 'nineteen',
        17: 'seventeen',
        16: 'sixteen',
        15: 'fifteen',
        14: 'fourteen',
        13: 'thirteen',
        12: 'twelve',
        11: 'eleven',
        10: 'ten',
        9: 'nine',
        8: 'eight',
        7: 'seven',
        6: 'six',
        5: 'five',
        4: 'four',
        3: 'three',
        2: 'two',
        1: 'one',
        0: ''

    def __init__(self, num):
        self.num = num
        self.words = 'zero' if num == 0 else self.wordify(num)

    def wordify(self, num):
        return ' '.join(map(lambda (i, chunk): self.wordify_chunk(chunk, i),

    def chunkify(self, num):
        rev = str(num)[::-1]
        rev_chunks = ([rev[i:i + 3] for i in range(0, len(rev), 3)])[::-1]
        return map(lambda x: int(x[::-1]), rev_chunks)

    def wordify_chunk(self, chunk, i):
        hundreds_digit, left_over = divmod(chunk, 100)
        hundreds = self.get_val(hundreds_digit)

        tens_digit, ones_digit = divmod(left_over, 10)
        if left_over > 10 and left_over < 20:
            tens = self.get_val(left_over)
            ones = None
            tens = self.get_val(tens_digit * 10)
            ones = self.get_val(ones_digit)

        word_chunk = self.frmt_chunk(hundreds, tens, ones)
        units = self.get_units(len(self.chunkify(self.num)) - 1 - i)
        return word_chunk + ' ' + units if word_chunk else ''

    def frmt_chunk(self, hundreds, tens, ones):
        chunk = ''
        if hundreds:
            chunk += hundreds + ' hundred '
        if hundreds and tens:
            chunk += 'and '
        if tens:
            chunk += tens
        if tens and ones:
            chunk += '-'
        if ones:
            chunk += ones
        return chunk

    def check_valid(self, num):
        if num < 0 or num > 999999999999:
            raise AttributeError

    def get_units(self, d):
        return self.get_val(1000 ** d) if 1000 ** d > 1 else ''

    def get_val(self, d):
        return self.VALS[d]

def say(num):
    return Say(int(num)).words

Community comments

Find this solution interesting? Ask the author a question to learn more.

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?