0

I have a list with 5 elements, x+2, x^3+x^2+x+2, x^3+x^2+2, x^3+2x^2+2x+2, x^3+2x+2. I am trying to get a big list with elements like (x+2)(x^3+x^2+x+2), (x+2)(x^3+x^2+x+2)(x^3+x^2+2) and so on. One element multiply the other four to get a new element. The only way I know is to use For loop to do it, but it doesn't give me the right list. Here is what I have:

L = ['x+2','x^3+x^2+x+2','x^3+x^2+2','x^3+2x^2+2x+2','x^3+2x+2']

for i in range(0,len(L)): 
    for j in range(1,len(L)):
        for k in range(2,len(L)):
            for l in range(3,len(L)):
                for m in range(4,len(L)):
                    print L[i],L[j],L[k],L[l],L[m]

I have many repeat elements, I want to know to how to avoid to have those repeat elements while generate the list. Can someone tell me how to do it?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Simple
  • 135
  • 6

2 Answers2

3

You can use combinations function to get all combinations of a list:

from itertools import combinations
    result = []
    for i in range(1,len(L)):
        result.append(list(combinations(L,i))
    result # [[('x+2',), ('x^3+x^2+x+2',), ('x^3+x^2+2',), ('x^3+2x^2+2x+2',), ('x^3+2x+2',)], [('x+2', 'x^3+x^2+x+2'), ('x+2', 'x^3+x^2+2'), ('x+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2'), ('x^3+x^2+x+2', 'x^3+2x^2+2x+2'), ('x^3+x^2+x+2', 'x^3+2x+2'), ('x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x^3+x^2+2', 'x^3+2x+2'), ('x^3+2x^2+2x+2', 'x^3+2x+2')], [('x+2', 'x^3+x^2+x+2', 'x^3+x^2+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+2x+2'), ('x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+x^2+2', 'x^3+2x+2'), ('x+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x^3+x^2+2', 'x^3+2x^2+2x+2', 'x^3+2x+2')], [('x+2', 'x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2', 'x^3+2x+2')]]
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
1

The word you're looking for is permutations

Python has that ability included in the itertools package

Community
  • 1
  • 1
en_Knight
  • 5,301
  • 2
  • 26
  • 46