Generating all combinations

pataphor pataphor at gmail.com
Tue Jun 2 02:53:34 EDT 2009


Mensanator wrote:

> I couldn't do that if they weren't subsets.

Right. Sometimes one just has to assume things are different even if 
they look the same on the surface. That is because else one wouldn't be 
able to produce the other generators. I guess it would also work the 
other way around, assuming things are the same even when they look 
different.

For example see my two functions:

def repeat_each(seq,n):
     while True:
         for x in seq:
             for i in range(n):
                 yield x

def repeat_all(seq,n):
     while True:
         for i in range(n):
             for x in seq:
                 yield x

(I should probably not smoke stuff before posting, but anyway)


They are the same, except for switching two lines of code. But for the 
second one ('repeat_all') the argument 'n' seems redundant. What does it 
even mean to repeat a sequence n times, and do that forever? Isn't that 
the same as just repeating the sequence itself, forever? So that's how 
we arrive at itertools.cycle . The second argument is there, but it 
would be foolish to include it, so it is left out.

But now let's look at how itertools.repeat should really be. It should 
look like 'repeat_each' above. Here second argument ('n') *is* 
necessary, or else the generator would just infinitely repeat only the 
first element of the sequence, which is obviously nonsense. But that is 
exactly why itertools.repeat does not accept a sequence (like cycle, its 
virtual brother) but instead it has degenerated into something that just 
repeats only one thing n times, which is stupid.

So to set things right one has to forget everything and just write 
complete balderdash if necessary, if it only leads to finally 
understanding how the two are related. Then one can see that 
itertools.repeat should be an infinite generator *on sequences* that 
however still needs a second argument specifying how many times each 
individual item should be repeated, and that itertools.cycle's second 
argument is there but hidden.

P.





More information about the Python-list mailing list