Project Euler 8: Find the largest product of 13 consecutive digits.
Project Euler 8 Solution Problem Description
Find the greatest product of 13 consecutive digits for a large number.
Convert the strings to a list of single digits and find the maximum product taking into consideration all 13-digit contiguous groups. You could map zeros as their group’s product would be zero, or search the space for groups with large factors (e.g., nines and eights) if you were so inclined. But, hey, this same algorithm solved the much more aggressive HackerRank version just fine.
80% of the Python solutions listed in the Project Euler forum are wrong as they don’t consider the last digit in the search space. Because the solution to this problem lies in the middle of the search space, these programs calculate a correct response. If you were to run them with the following parameters they would fail by erroneously produce zero as an answer instead of 18:
d = [0,0,0,1,9,2]
L = 3
Further, many of these programs would return an error or zero(a distinct possibility) which could be misleading; it’s better to return some indication that an answer cannot be calculated, such as “None,” to indicate that a maximum product could not be found for 13 digits:
d = [0,0,0,1,9,2]
L = 13
solves all test cases
Project Euler 8 SolutionRuns < 0.002 seconds in Python 2.7.
Use this link to get the Project Euler 8 Solution Python 2.7 source.
AnswerSlowly swipe from either end beginning with the white vertical bar to get an idea of the starting or ending digits. For less drama, just double click the answer area. The distance between the two bars will give you an idea of the magnitude. Touch devices can tap and hold the center of the box between the two bars and choose define to reveal the answer.
- PEP 8 is the style guide for Python. It describes the preferred methods for formatting Python source code for a consistent appearance. We do our best to follow those guidelines to make the code as readable as possible.
But sometimes lines of Python can get a bit confusing, such as:
d = map(int, ''.join(line.rstrip() for line in open('pe8.txt')))
and may need further explanation:
The above line opens and reads the file “pe8.txt” (the second tab next to the main.py tab in the Trinket window) and concatenates each line into one long string by stripping (rstrip) the new line character (\n) from the end of the lines. Finally, each character is separated and converted to an integer before being added to a list named d.