0

I'm trying to dig into some code I found online here to better understand Python.

This is the code fragment I'm trying to get a feel for:

from itertools import chain, product

def generate_groupings(word_length, glyph_sizes=(1,2)):
    cartesian_products = (
        product(glyph_sizes, repeat=r)
        for r in range(1, word_length + 1)
    )

Here, word_length is 3.

I'm trying to evaluate the contents of the cartesian_products generator. From what I can gather after reading the answer at this SO question, generators do not iterate (and thus, do not yield a value) until they are called as part of a collection, so I've placed the generator in a list:

list(cartesian_products)
Out[6]: 
[<itertools.product at 0x1025d1dc0>,
 <itertools.product at 0x1025d1e10>,
 <itertools.product at 0x1025d1f50>]

Obviously, I now see inside the generator, but I was hoping to get more specific information than the raw details of the itertools.product objects. Is there a way to accomplish this?

Community
  • 1
  • 1
nerdenator
  • 1,265
  • 2
  • 18
  • 35
  • 1
    `itertools.product` objects don't expose anything useful for introspection. You could iterate over them to look at what they produce, but then they're exhausted and unuseable for the rest of the algorithm... not that it matters, because you already exhausted `cartesian_products`. – user2357112 May 17 '17 at 19:22

1 Answers1

1

if you don't care about exhausting the generator, you can use:

list(map(list,cartesian_products))

You will get the following for word_length = 3

Out[1]:
[[(1,), (2,)],
 [(1, 1), (1, 2), (2, 1), (2, 2)],
 [(1, 1, 1),
  (1, 1, 2),
  (1, 2, 1),
  (1, 2, 2),
  (2, 1, 1),
  (2, 1, 2),
  (2, 2, 1),
  (2, 2, 2)]]
DSLima90
  • 2,680
  • 1
  • 15
  • 23