# Largest product in a series in python

You can use a generator expression within max function and a proper key function which calculate the product of your sub digits. For that aim you can use map function to convert the digits to integer and reduce (in python 3.X functools.reduce) to calculate the product of the integers.

>>> max((digits[i:i+13] for i in xrange(0, len(digits) - 12)), key=lambda x: reduce(mul, map(int, x)))
'5576689664895'


Note that if you have new line character between your digits you need to remove them using str.replace() method.

digits = digits.replace('\n', '')


## More optimized approach:

Since you are dealing with 13 digit each time you can use a container in order to preserve your digits in each iteration, and the best choice here would be deque() form collections module with maxlen=13 which it's pop and push operation's order is O(1). Then you can calculate the product of the first 13 digit and at each push and pop your initial product should be divided by popped item and multiple by pushed item. and in each iteration you can just preserve the sequence with maximum product.

from operator import mul
from collections import deque
from copy import copy

def cal_max_prod(container, current_product):
max_container = {'seq': copy(container), 'prod': current_product}
for i in digits[13:]:
popped_item = int(container.popleft())
container.append(i)
try:
push_item = int(i)
current_product = (current_product / popped_item) * push_item
except ZeroDivisionError:
if '0' not in container:
current_product = reduce(mul, map(int, container))
else:
if current_product > max_container['prod']:
max_container['prod'] = current_product
max_container['seq'] = copy(container)

return ''.join(max_container['seq'])


Demo:

container = deque(digits[:13], maxlen=13)
current_product = reduce(mul, map(int, container))
print cal_max_prod(container, current_product)
5576689664895