1

I am trying to compare all combinations of the values in N lists. Each list is identical holding values 1 through 9 in order. I am having a very hard time figuring out how to code this because I cannot create N nested loops beforehand. N is user defined and won't be known until run time. The place I always get stuck on is trying to iterate through every possible combination of values in an arbitrary number of lists using a fixed number of loops.

Any suggestions? I've been trying for an hour now to figure this out. I'm sure it is something simple I am missing.

Andrew
  • 13
  • 2
  • If you mean 'how can I compute the cartesian product', I've asked a question before, on how to do it iteratively: http://stackoverflow.com/questions/2419370/how-can-i-compute-a-cartesian-product-iteratively. However, a simpler solution is to use recursion, and the best one is to use the function product() from the module itertools. – Federico A. Ramponi Sep 18 '10 at 02:51
  • Check also this question: http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python – Federico A. Ramponi Sep 18 '10 at 02:52
  • Ah, I did not know doing this had a name. Thanks you both for the links. I will search more carefully before posting next time. – Andrew Sep 18 '10 at 03:12

1 Answers1

5
import itertools
for combo in itertools.product(xrange(1, 10), repeat=N):
  ...
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539