[Tutor] Project Euler #8

Nick Shemonsky n.shemonsky at gmail.com
Fri May 31 22:49:40 CEST 2013


Thanks for the responses. I am using python 2.7.  I'm not new to
programming but might as well be... I last programmed heavily about a
decade ago in college. I was a MIS major so I did my fair share of
c++, sql, and php work but now I'm a windows sys admin so I haven't
used it much at all in a long time. Using powershell a bunch recently
got me back into scripting and that triggered the itch to get back
into coding so I'm starting with python to see where it goes. The
thought of combining my love of computing with my love of music/audio
and eventually doing audio programming would be sweet, but DSP is some
heavy stuff and I'm no electrical engineer!

Anyway, with your suggestions I got it working! Hopefully once I get a
little bit more knowledge under my belt I can start offering some
assistance to others around here.

Here's the final code... I kept the if statement that way if I throw
in a random series of numbers that isn't evenly divisible by 5, it'll
always work itself out. And this answered the 1000 digit problem
without issue.

str_num = '1234567890'
n = 5
strings = [str_num[i:i+5] for i in xrange(0, len(str_num)) if
len(str_num[i:i+5])==5]

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

def get_max(y):
    products = [product(substr) for substr in strings]
    return max(products)

print get_max(str_num)


Alan,

I did stumble upon using reduce in place of writing my own function
for getting the product when googling around but I didn't really
understand what it was doing so I refrained from using it. More to
explore I guess...


Thanks again guys!

On Fri, May 31, 2013 at 4:10 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 31/05/13 19:23, Nick Shemonsky wrote:
>
>> 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
>
>
> You are probably right if it is a giant list.
>
>
>> 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
>
>
> You define a parameter x but don't use it?
>
> You could use reduce here:
>
> import operator
> ...
> def product(intlist):
>     return reduce(operator.mul, intlist)
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list