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

rootulp's solution

to Wordy 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.

Parse and evaluate simple math word problems returning the answer as an integer.

Iteration 1 β€” Addition

Add two numbers together.

What is 5 plus 13?

Evaluates to 18.

Handle large numbers and negative numbers.

Iteration 2 β€” Subtraction, Multiplication and Division

Now, perform the other three operations.

What is 7 minus 5?


What is 6 multiplied by 4?


What is 25 divided by 5?


Iteration 3 β€” Multiple Operations

Handle a set of operations, in sequence.

Since these are verbal word problems, evaluate the expression from left-to-right, ignoring the typical order of operations.

What is 5 plus 13 plus 6?


What is 3 plus 2 multiplied by 3?

15 (i.e. not 9)

Bonus β€” Exponentials

If you'd like, handle exponentials.

What is 2 raised to the 5th power?


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 wordy_test.py
  • Python 3.4+: pytest wordy_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 wordy_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/wordy 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.


Inspired by one of the generated questions in the Extreme Startup game. https://github.com/rchatley/extreme_startup

Submitting Incomplete Solutions

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


import unittest

from wordy import calculate

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

class WordyTest(unittest.TestCase):
    def test_addition(self):
        self.assertEqual(calculate("What is 1 plus 1?"), 2)

    def test_more_addition(self):
        self.assertEqual(calculate("What is 53 plus 2?"), 55)

    def test_addition_with_negative_numbers(self):
        self.assertEqual(calculate("What is -1 plus -10?"), -11)

    def test_large_addition(self):
        self.assertEqual(calculate("What is 123 plus 45678?"), 45801)

    def test_subtraction(self):
        self.assertEqual(calculate("What is 4 minus -12?"), 16)

    def test_multiplication(self):
        self.assertEqual(calculate("What is -3 multiplied by 25?"), -75)

    def test_division(self):
        self.assertEqual(calculate("What is 33 divided by -3?"), -11)

    def test_multiple_addition(self):
        self.assertEqual(calculate("What is 1 plus 1 plus 1?"), 3)

    def test_addition_then_subtraction(self):
        self.assertEqual(calculate("What is 1 plus 5 minus -2?"), 8)

    def test_multiple_subtraction(self):
        self.assertEqual(calculate("What is 20 minus 4 minus 13?"), 3)

    def test_subtraction_then_addition(self):
        self.assertEqual(calculate("What is 17 minus 6 plus 3?"), 14)

    def test_multiple_multiplication(self):
            calculate("What is 2 multiplied by -2 multiplied by 3?"), -12)

    def test_addition_then_multiplication(self):
        self.assertEqual(calculate("What is -3 plus 7 multiplied by -2?"), -8)

    def test_multiple_division(self):
            calculate("What is -12 divided by 2 divided by -3?"), 2)

    def test_unknown_operation(self):
        with self.assertRaisesWithMessage(ValueError):
            calculate("What is 52 cubed?")

    def test_non_math_question(self):
        with self.assertRaisesWithMessage(ValueError):
            calculate("Who is the President of the United States?")

    # Additional tests for this track

    def test_missing_operation(self):
        with self.assertRaisesWithMessage(ValueError):
            calculate("What is 2 2 minus 3?")

    def test_missing_number(self):
        with self.assertRaisesWithMessage(ValueError):
            calculate("What is 7 plus multiplied by -2?")

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

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

if __name__ == '__main__':
class Calculator:

    OPERATORS = {"plus": "+",
                 "minus": "-",
                 "multiplied by": "*",
                 "divided by": "/",
                 "What is ": "",
                 "?": ""}

    VALID_TOKENS = set(OPERATORS.values())

    def __init__(self, inp):
        self.inp = inp
        self.tokenized = self.tokenize(inp)
        self.tokens = self.tokenized.split(" ")

    def calculate(self):
        if not self.valid():
            raise ValueError
        operator_stack = self.operator_stack()
        num_stack = self.num_stack()
        while len(operator_stack) > 0:
            operator = operator_stack.pop(0)
            num1 = num_stack.pop(0)
            num2 = num_stack.pop(0)
            num_stack.insert(0, self.evaluate(operator, num1, num2))
        return num_stack.pop(0)

    def evaluate(self, operator, num1, num2):
        return eval(str(num1) + operator + str(num2))

    def num_stack(self):
        return map(int, filter(self.digit, self.tokens))

    def operator_stack(self):
        return filter(self.operator, self.tokens)

    def valid(self):
        return (self.valid_elements() and
                not self.consecutive_tokens() and
                not self.consecutive_digits())

    def consecutive_tokens(self):
        return any(self.operator(i) and self.operator(j) for i, j in

    def consecutive_digits(self):
        return any(self.digit(i) and self.digit(j) for i, j in

    def slices_of_two(self):
        return zip(self.tokens, self.tokens[1:])

    def valid_elements(self):
        return all(self.valid_element(element) for element in self.tokens)

    def valid_element(cls, element):
        return element in cls.VALID_TOKENS or cls.digit(element)

    def tokenize(cls, inp):
        for operator, token in cls.OPERATORS.items():
            inp = inp.replace(operator, token)
        return inp

    def digit(element):
        return element.lstrip("-").isdigit()

    def operator(cls, element):
        return element in cls.OPERATORS.values()

def calculate(inp):
    return Calculator(inp).calculate()

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?