Home > Back-end >  Flatten array recursively in python
Flatten array recursively in python

Time:10-13

from permutations of array I have an array like this:

[['a', [['b', ['c']], ['c', ['b']]]], ['b', [['a', ['c']], ['c', ['a']]]], ['c', [['a', ['b']], ['b', ['a']]]]]

which means for 'a' I have 'b' and 'c' and for inner 'b' I have 'c' etc. I am confused how to make a new array which is representing this logic (not only for three variables) and I need it to look like this:

[['a','b','c'],['a','c','b'],['b','a','c'],['b','c','a'],['c','a','b'],['c','b','a']]

Is it somehow possible? Thank you!

CodePudding user response:

You can write a recursive function in order to flatten the list.

def flatten(permutations):
    flattens = []
    for permutation in permutations:
        if len(permutation) == 2:
            flattens.extend([[permutation[0], *j] for j in flatten(permutation[1])])

        else:
            flattens.extend(permutation)

    return flattens


if __name__ == '__main__':
    permutations = [['a', [['b', ['c']], ['c', ['b']]]], ['b', [['a', ['c']], ['c', ['a']]]], ['c', [['a', ['b']], ['b', ['a']]]]]
    print(flatten(permutations))

Output:

[['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]

CodePudding user response:

Slightly shorter recursive solution with a generator:

data = [['a', [['b', ['c']], ['c', ['b']]]], ['b', [['a', ['c']], ['c', ['a']]]], ['c', [['a', ['b']], ['b', ['a']]]]]
def full_combos(d, c = []):
   if all(not isinstance(j, list) for j in d):
      yield from [c [j] for j in d]
   else:
      yield from [j for a, b in d for j in full_combos(b, c [a])]

print(list(full_combos(data)))

Output:

[['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]

CodePudding user response:

The answer by vikas soni is great if you start from your first array. But if you start from a list of elements then the task is much simpler:

from itertools import permutations
ls = ["a", "b", "c"]
list(permutations(ls, len(ls)))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

ls2 = ["a", "b", "c", "d", "e"]
len(list(permutations(ls, len(ls))))
120
  • Related