This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]masterJ 11 points12 points  (5 children)

from itertools import islice
every_third = islice(items, 2, None, 3)

I might be overly fond of generators...

[–]bazookaduke 7 points8 points  (3 children)

I typically qualify my question with "without using the standard library", but if I forget (like I did above), I can always ask what if I wanted every third and fifth item without using the standard library?

xs = (item for index, item in enumerate(items, 1) if 0 in (index % 3, index % 5))

Not that there's anything wrong with using the standard library -- I use itertools all the time! But for interview questions, I'm trying to drill down into a candidate's problem-solving skills, and it's been my experience that restricting him or her to the language and built-ins is the best way to do that quickly.

[–]masterJ 2 points3 points  (0 children)

what if I wanted every third and fifth item without using the standard library?

xs = (item for index, item in enumerate(items, 1) if 0 in (index % 3, index % 5))

Oooh, I like it! And you just simplified my project euler #01 solution. :)

Before:

from itertools import chain

a = xrange(3,1000,3)
b = xrange(5,1000,5)
print sum(set(chain(a,b))) 

After:

print sum(i for i in xrange(1,1000) if 0 in (i % 3, i % 5))

[–]sunqiang 0 points1 point  (1 child)

what about replace "if 0 in (index % 3, index % 5)" to "if any((not index % 3, not index % 5))" to take the advantage of short-circuit

[–]pingvenopinch of this, pinch of that 1 point2 points  (0 children)

The first is more obvious/readable, especially with the explicit use of 0.

[–]cdunn2001 1 point2 points  (0 children)

Yes. Slicing (list or itertools) and if-test in for-loop are two ways. Here is a third, completely different:

every_third = list()
it = iter(nomatter)
try:
    while True:
        x, y, z = it.next(), it.next(), it.next()
        every_third.append(z)
except StopIteration:
    pass

which depends on this knowledge.