Search code examples
pythontreepermutationpython-itertools

Creating permutations of tree diagram dynamically and scalable


I am trying to create permutations which follows a datatree design in Python. The root should be dynamically and could contain a list of lists.

This image shows how the permutations should be created

Arrows show allowed combinations.

This image explains what could be combined in each level

I have tried using itertools.permutations without getting the right results as the lists are too deep.

  • The array should be handled dynamically as the size of the lists could differ on all levels.
  • The items in the different lists on each level should not be combined but the items inside of each list must be.
  • Only one list should be included in the combination from each layer

List = List with one or more strings inside Level = List with multiple or one list inside

Example code of input:

[
 [
  ["8F10"], ["8F12"], ["8F11"]
 ],
 [
  ["8F10"], ["8F12"], ["8F11"]
 ],
 [
  ["8F10"], ["8F12"], ["8F11"]
 ],
 [
  ["FW03", "8F10"], ["FW03", "8F12"], ["FW03", "8F11"]
 ],
 [
  ["8F12"], ["8F10"], ["8F11"]
 ],
 [
  ["8F10", "KE04"], ["8F11", "KE04"], ["8F12", "KE04"]
 ],
 [
  ["8F11"], ["8F12"], ["8F10"]
 ],
 [
  ["8F10"], ["8F11"], ["8F12"]
 ],
 [
  ["8F10"], ["8F11"], ["8F12"]
 ],
 [
  ["9T03", "8F10"], ["9T03", "8F11"], ["9T03", "8F12"]
 ]
]

EDIT:

Expected results could be a list of tuples with each permutation (combination) like itertools.permutations.

Example of expected results (one tuple):

[
 (["8F10"], ["8F10"], ["8F10"], ["FW03"], ["8F10"], ["8F12"], ["8F10"], ["KE04"], ["8F11"], ["8F10"], ["8F10"], ["9T03"], ["8F10"]), 
 (["8F10"], ["8F12"], ["8F10"], ["FW03"], ["8F10"], ["8F12"], ["8F10"], ["KE04"], ["8F11"], ["8F10"], ["8F10"], ["9T03"], ["8F10"]), 
 ...
]

Input and output can be adjusted (if it's list, tuple, dictionary and so on) but the important task is to get all permutations/combinations possible.

The grouping cannot be adjusted, for example ["FW03", "8F10"] cannot be split as they are depended of each other.


Solution

  • Let's say your input is available by the name data, then the following will create an iterator over the possible combinations:

    it = (tuple(itertools.chain(*x)) for x in itertools.product(*data))