-2

I used recursive to get combination of certain elements.

I get combination when indexerror occurs.(in except: part)

For a = ['a1', 'a2', 'a3'], b = ['b1', 'b2'], c = ['c1', 'c2', 'c3']

I want to get possible combinations which are

[['a1', 'b1', 'c1'],['a1', 'b1', 'c2'],['a1', 'b1', 'c3'],['a1', 'b2', 'c1'],['a1', 'b2', 'c2'],['a1', 'b2', 'c3'],['a2', 'b1', 'c1'],['a2', 'b1', 'c2'],['a2', 'b1', 'c3'],['a2', 'b2', 'c1'],['a2', 'b2', 'c2'],['a2', 'b2', 'c3'],['a3', 'b1', 'c1'],
['a3', 'b1', 'c2'],['a3', 'b1', 'c3'],['a3', 'b2', 'c1'],['a3', 'b2', 'c2'],['a3', 'b2', 'c3']]

However, the result is not what I want.

[['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3'], ['a3', 'b2', 'c3']]

Only last combination comes out.

Here is my code.. I would thank you to show me proper way.

a = ['a1', 'a2', 'a3']
b = ['b1', 'b2']
c = ['c1', 'c2', 'c3']

def loop(lst, combi, combi_set, index=0):
    try:
        for a in lst[index]:
            if len(combi) == len(lst):
                for n, i in enumerate(combi):
                    if i.startswith(a[0]):
                        combi[n] = a
            else:
                combi.append(a)

            loop(lst, combi, combi_set, index=index + 1)

    except IndexError:
        print(combi)
        combi_set.append(combi)
        return

set = []
loop([a, b, c], [], set, 0)
print(set)
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
chacha
  • 1
  • 1
  • Is this a specific excersise or do you just need the carthesian product? In the latter case, use `itertools.product(a, b, c)`, don't re-invent this wheel. – Martijn Pieters Aug 09 '17 at 06:41
  • You are re-using the same list over and over and over again. When you append that list to `combi_set`, you end up with a list of references to **one list**. Create copies instead. – Martijn Pieters Aug 09 '17 at 06:46

1 Answers1

-1

import itertools

i = [['a1','a2','a3'],['b1', 'b2'],['c1','c2','c3']]

print list(itertools.product(*i))