[Tutor] Project Euler #8

Nick Shemonsky n.shemonsky at gmail.com
Fri May 31 20:23:42 CEST 2013


Hey there everybody. I'm new to python and am attempting to teach
myself to code while brushing up on my math skills via the problems at
projecteuler.net. My solutions thus far have been mostly brute force
and this is no exception but I'm having an issue with tackling some
iteration in the problem.

Essentially, the problem is to find the largest product of 5
consecutive digits in a random series of numbers. I'm trying to get
things working on a very small string to start... my code thus far is
below.

I begin by getting a list of strings from the original string, only
keeping those that are 5 digits long... then those numbers are
converted to integers and I get the product with the product function.
 As you can see, I'm currently doing it only for the string of 12345
stored at strings[0]. If I run that list comprehension as [int(i) for
i in strings], I get a new list of all the integers I want; 12345,
23456, 34567, etc... but I can no longer iterate through to multiply
them all together...

I feel like I need to either pull each individual string apart first
and temporarily store it then convert each to an int and get the
product or instead, just find a way to iterate through the members of
a member of a list... I've read up on a bunch of stuff regarding
map(), zip() and enumerate() but none of it seems to be applicable
here or maybe I'm misunderstanding it.

Once I have a list of products a simple max() should do the trick...
or maybe it'd be quicker to compare a to b through each iteration and
just keep the larger product rather than creating a giant list of
products once I get this step working? Any ideas towards the next step
would be much appreciated.

str_num = '1234567890'
n = 5

strings = [str_num[i:i+5] for i in range(0, len(str_num)) if
len(str_num[i:i+5])==5]
integers = [int(i) for i in strings[0]]

def product(x):
    p = 1
    for n in integers:
        p*=n
    return p

print product(integers)

Thanks in advance!

Nick


More information about the Tutor mailing list