[Tutor] Project Euler #8

Dave Angel davea at davea.name
Fri May 31 23:03:04 CEST 2013


On 05/31/2013 04:49 PM, Nick Shemonsky wrote:
>    <SNIP>
> 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]

My earlier comment here applies regardles of whether the total size is 
divisible by 5.  You just want to stop when the substring ends at the 
end of the full string.  One advantage you have is that you probably 
won't be as likely to be off-by-one.

Another things that's frequently useful is shown by your n=5.  Instead 
of repeating that 5 in multiple places, put in one "const" and use that 
const wherever you would otherwise by hardcoding the 5.

LEN=5
strings = [str_num[i:i+LEN] for i in xrange(0, len(str_num)-LEN+1)]

Notice that I needed -LEN+1 there, and that it'd be easy to be off by 
one.  With practice, you begin to expect that, and always test.  And 
sometimes it's easier to write more complex but understandable code than 
it is to explain the +1 there.



-- 
DaveA


More information about the Tutor mailing list