1

For starters, I read this: all permutations of a binary sequence x bits long

This is similar to what I want, but I don't want to generate all permutations in advance. What I want is more of a generator that I can step through and stop whenever I want (for efficiency reasons, I have cutoff conditions where I want to halt).

I was wondering if there is an elegant way to do this Python. The answers to the question above all involved ".join"s, but I don't think that will work here. I assume I need to use itertools.

Any ideas?

Community
  • 1
  • 1
Chris Chambers
  • 1,367
  • 21
  • 39
  • 1
    Python has _very_ elegant generators. Just google "python generator". – alexis Mar 29 '15 at 21:30
  • @alexis This is interesting: https://wiki.python.org/moin/Generators. However, I have never worked with generators before, do you mind showing me how it would work in my case? – Chris Chambers Mar 29 '15 at 21:32
  • 1
    [The python tutorial](https://docs.python.org/3/tutorial/classes.html#generators) is the place to start. But see my answer. – alexis Mar 29 '15 at 21:38

1 Answers1

4

Since you like the solution in the answer you link to, here's the generator version:

for pattern in ("".join(seq) for seq in itertools.product("01", repeat=3)):
    ...

Using parens instead of square brackets [ ... ] gives you a generator that creates the values on demand.

It's easy to turn almost any function into generator; see the python tutorial for the details.

alexis
  • 48,685
  • 16
  • 101
  • 161