0

I'm trying to write a program in Python for solving PictoLogic games. I'm currently trying to write all possible boards from the horizontal numbers. So, I've got something like this:

lines = [[all possible combos for line 1], [same for line 2], [same for line 3], etc]

This lists are of different lenghts, and I also have another version in which they'll be a dict (with the indexex 1, 2, 3, etc.)

The idea would be to get all possible combinations of boards. For example:

lines = [["aa", "ab", "ba"], ["cc"]]

would lead into

[["aa", "cc"], ["ab", "cc"], ["ba", "cc"]]

That, but with lists of different lenghts and not knowing in advance the number of lines. Thanks in advance, and sorry for bad english

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
Knexator
  • 21
  • 4

3 Answers3

2

You can use itertools.product and pass the sub-list to this unction with an unpacking operation (*):

>>> lines = [['aa', 'ab', 'ba'], ['cc']]
>>> from itertools import product
>>> list(product(*lines))
[('aa', 'cc'), ('ab', 'cc'), ('ba', 'cc')]

And if you want the result as list you can use map function :

>>> map(list,product(*lines))
[['aa', 'cc'], ['ab', 'cc'], ['ba', 'cc']]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
2

Consider this way:

a = ['a', 'b', 'c']
b = ['x', 'y']

print [[i,j] for i in a for j in b]
>> [['a', 'x'], ['a', 'y'], ['b', 'x'], ['b', 'y'], ['c', 'x'], ['c', 'y']]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

You would do this with itertools.product and the unpacking operator *:

lines = [["aa", "ab", "ba"], ["cc"]]
from itertools import product
print list(list(t) for t in product(*lines))
# >>> [['aa', 'cc'], ['ab', 'cc'], ['ba', 'cc']]
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69