[Tutor] Project Euler #8

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Sat Jun 1 19:01:52 CEST 2013


Dave Angel <davea <at> davea.name> writes:

> 
> > 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]
> 
> If you changed the range() size, you could eliminate the extra if test. 
>   After all, the only ones that'll be short are the last 4.  Also, 
> xrange is better than range, if you ever try this on a really big 
> dataset.  Good habit to get into, and in Python 3.x, the original range 
> is gone, and xrange is called range.
> 
>     strings = [str_num[i:i+5] for i in xrange(0, len(str_num-4)) ]
>
 
Of course, if you're really concerned about the size of your dataset, then
you should combine xrange (or range in Python 3) with a generator expression
instead of a list comprehension to yield substrings only one at a time.
This is very easy to do: just replace your square brackets with parentheses:
strings = (str_num[i:i+5] for i in xrange(0, len(str_num-4)))

Since this is in expression you might find useful again for other tasks, you
could encapsulate it in a (very short) function:

def slider (s, window):
    return (s[i:i+window] for i in range(0, len(s)-window+1))

that you can use conveniently in a for loop:

for substr in slider(str_num, 5):

or in a comprehension, like:

products = [product(substr) for substr in slider(str_num, 5)]

for your code.
Best,
Wolfgang



More information about the Tutor mailing list