circular iteration

  • Thread starter Flavio codeco coelho
  • Start date
F

Flavio codeco coelho

hi,

is there a faster way to build a circular iterator in python that by doing this:

c=['r','g','b','c','m','y','k']

for i in range(30):
print c[i%len(c)]

thanks,

Flávio
 
D

Duncan Booth

Flavio said:
hi,

is there a faster way to build a circular iterator in python that by
doing this:

c=['r','g','b','c','m','y','k']

for i in range(30):
print c[i%len(c)]

thanks,

Flávio
import itertools
c=['r','g','b','c','m','y','k']
circ = itertools.cycle(c)
for i in range(30):
print circ.next(),


r g b c m y k r g b c m y k r g b c m y k r g b c m y k r g
 
F

Fredrik Lundh

Flavio codeco coelho said:
is there a faster way to build a circular iterator in python that by doing this:

c=['r','g','b','c','m','y','k']

for i in range(30):
print c[i%len(c)]

have you benchmarked this, and found it lacking, or are you just trying
to optimize prematurely?

</F>
 
A

Alex Martelli

Simon Brunning said:
is there a faster way to build a circular iterator in python that by doing this:

c=['r','g','b','c','m','y','k']

for i in range(30):
print c[i%len(c)]

I don''t know if it's faster, but:
import itertools
c=['r','g','b','c','m','y','k']
for i in itertools.islice(itertools.cycle(c), 30):
... print i

Whenever you're using itertools, the smart money's on "yes, it's
faster";-).

E.g., on a slow, old iBook...:

kallisti:~ alex$ python -mtimeit -s'c="rgbcmyk"' 'for i in range(30):
c[i%len(c)]'
10000 loops, best of 3: 47 usec per loop

kallisti:~ alex$ python -mtimeit -s'c="rgbcmyk"; import itertools as it'
'for i in it.islice(it.cycle(c),30): i'
10000 loops, best of 3: 26.4 usec per loop

Of course, if you do add back the print statements they'll take orders
of magnitude more time than the cyclic access, so /F's point on
premature optimization may well be appropriate. But, if you're doing
something VERY speedy with each item you access, maybe roughly halving
the overhead for the cyclic access itself MIGHT be measurable (maybe
not; it IS but a few microseconds, after all).

I like itertools' approach because it's higher-abstraction and more
direct. Its blazing speed is just a trick to sell it to conservative
curmudgeons who don't see abstraction as an intrinsic good -- some of
those are swayed by microseconds;-)


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top