[Chicago] Printing out the Cartesian product.

Lewit, Douglas d-lewit at neiu.edu
Thu Jul 16 00:15:23 CEST 2015


Hi everyone,

I need some advice on how to do something.  Let's say that I want to print
out the Cartesian product of the integers 1 to 4.  It would look something
like this:

1, 1, 1, 1
1, 1, 1, 2
1, 1, 1, 3
1, 1, 1, 4
1, 1, 2, 1
1, 1, 2, 2
1, 1, 2, 3
1, 1, 2, 4
1, 1, 3, 1
1, 1, 3, 2
1, 1, 3, 3, etc, etc until finally we have
..............
4, 4, 4, 3
4, 4, 4, 4

This is NOT a permutation because repetition is allowed.  Nor is it a
combination because for example 1, 1, 1, 2 is distinct from 2, 1, 1, 1.  I
believe this is technically called a Cartesian product.

I know of two ways to do this:

Method #1:

*for a in range(1, 5):*
*     for b in range(1, 5):*
*          for c in range(1, 5):*
*                for d in range(1, 5):*
*                      print( a, end = ", " )*
*                      print( b, end = ", " )*
*                      print( c, end = ", " )*
*                      print( d, end = "\n" )*


The above works just fine!  But there's a problem.  What if let's say I
want the Cartesian product of all the integers from 1 to 10?  That means
working with 10 nested for-loops!  That's insane!  It's tedious to write
and probably even worse for the person who is reading it.  So this method
is limited to smaller examples.

Method #2:

Cheat by using Python's itertools package!  (Or is it a library?  What's
the difference between a package and a library?)

import itertools

carProduct = itertools.product([1, 2, 3, 4], repeat = 4)

*try:*
*     while True:*
*               print( next(carProduct) )*
*except StopIteration:*
*      pass*

This method is short and sweet!  It works great!  But it's really cheating
in the sense that the programmer is taking advantage of code that has
already been written.  (I have nothing against doing that!  But in a CS
class if I write down that answer on an exam do you think the professor is
going to give me any credit?  Probably not!!!  LOL! )

Is there some other way?  I'm guessing that I would need a for-loop that
contains a recursive function.  Or.... maybe a recursive function that
contains a for-loop?  I really don't know.  I've been struggling with this
for a couple days now and I can't think of a solution.  Can someone please
enlighten me?

Gratefully,

Douglas.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20150715/757157c1/attachment.html>


More information about the Chicago mailing list