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

rootulp's solution

to Largest Series Product in the Python Track

Published at Jul 13 2018 · 1 comment
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 string of digits, calculate the largest product for a contiguous substring of digits of length n.

For example, for the input '1027839564', the largest product for a series of 3 digits is 270 (9 * 5 * 6), and the largest product for a series of 5 digits is 7560 (7 * 8 * 3 * 9 * 5).

Note that these series are only required to occupy adjacent positions in the input; the digits need not be numerically consecutive.

For the input '73167176531330624919225119674426574742355349194934', the largest product for a series of 6 digits is 23520.

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 largest_series_product_test.py
  • Python 3.4+: pytest largest_series_product_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 largest_series_product_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/largest-series-product 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 Problem 8 at Project Euler http://projecteuler.net/problem=8

Submitting Incomplete Solutions

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


"""Tests for the largest-series-product exercise

Implementation note:
In case of invalid inputs to the 'largest_product' function
your program should raise a ValueError with a meaningful error message.

Feel free to reuse your code from the 'series' exercise!
import unittest

from largest_series_product import largest_product

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

class LargestSeriesProductTest(unittest.TestCase):
    def test_finds_the_largest_product_if_span_equals_length(self):
        self.assertEqual(largest_product("29", 2), 18)

    def test_can_find_the_largest_product_of_2_with_numbers_in_order(self):
        self.assertEqual(largest_product("0123456789", 2), 72)

    def test_can_find_the_largest_product_of_2(self):
        self.assertEqual(largest_product("576802143", 2), 48)

    def test_can_find_the_largest_product_of_3_with_numbers_in_order(self):
        self.assertEqual(largest_product("0123456789", 3), 504)

    def test_can_find_the_largest_product_of_3(self):
        self.assertEqual(largest_product("1027839564", 3), 270)

    def test_can_find_the_largest_product_of_5_with_numbers_in_order(self):
        self.assertEqual(largest_product("0123456789", 5), 15120)

    def test_can_get_the_largest_product_of_a_big_number(self):
                "73167176531330624919225119674426574742355349194934", 6),

    def test_reports_zero_if_the_only_digits_are_zero(self):
        self.assertEqual(largest_product("0000", 2), 0)

    def test_reports_zero_if_all_spans_include_zero(self):
        self.assertEqual(largest_product("99099", 3), 0)

    def test_rejects_span_longer_than_string_length(self):
        with self.assertRaisesWithMessage(ValueError):
            largest_product("123", 4)

    def test_reports_1_for_empty_string_and_empty_product_0_span(self):
        self.assertEqual(largest_product("", 0), 1)

    def test_reports_1_for_nonempty_string_and_empty_product_0_span(self):
        self.assertEqual(largest_product("123", 0), 1)

    def test_rejects_empty_string_and_nonzero_span(self):
        with self.assertRaisesWithMessage(ValueError):
            largest_product("", 1)

    def test_rejects_invalid_character_in_digits(self):
        with self.assertRaisesWithMessage(ValueError):
            largest_product("1234a5", 2)

    def test_rejects_negative_span(self):
        with self.assertRaisesWithMessage(ValueError):
            largest_product("12345", -1)

    def test_project_euler_big_number(self):
        series = (
        self.assertEqual(largest_product(series, 13), 23514624000)

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

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

if __name__ == '__main__':
def largest_product(digits, size):
    products = [reduce(lambda x, y: x * y, s, 1) for s in slices(digits, size)]
    return max(products)

def slices(digits, size):
    if len(digits) < size:
        raise ValueError
    return each_cons(map(int, list(digits)), size)

def each_cons(x, size):
    return [x[i: i + size] for i in range(len(x) - size + 1)]

Community comments

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

I love the conciseness!

How about operator.mul instead of lambda x, y: x * y?

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?