0

Not a duplicate of this answer because that answer deals with permuting literals, and this question refers to objects. Please refer to this question for what happens when permuting objects.

Using python 2.

I need to generate all possible permutations of an object list that includes the empty list, and then all permutations of 1 object, then with 2 and so on.

I have found a way to do this with a string:

import itertools
stuff = [1, 2, 3]
for idx in range(len(stuff)+1):
    for i in itertools.permutations('ABCD', idx):
        print i

Sample output:
()

('A',)

('B',)

('C',)

('D',)

('A', 'B')

('A', 'C')

('A', 'D')

('B', 'A')
.
.
.
.

('D', 'C', 'A')

('D', 'C', 'B')

What I need is to do this with a custom object list. I tried to apply the above algorithm to an objects list. My solution below:

originalObjectList = A list of many custom objects.
allPossibleOrderings=[]

for idx in range(len(originalObjectList)+1):
    originalObjectListOrderings = list(itertools.permutations(originalObjectList, idx))
    for objects in originalObjectListOrderings:
        allPossibleOrderings.insert(0, map(copy.copy,objects))

The problem with this implementation is that the allPossibleOrderings list doesn't contain all permutations, only the last 29. It's as if when I insert new permutations, it overwrites old ones.

Leonardo Lopez
  • 1,113
  • 6
  • 20
  • 39
  • 1
    The "duplicate" doesn't seem to be exactly the same, but the idea is the same. You just need to replace `combinations` with `permutations`. Also, your first example looks fine, but you strayed from copying the same procedure for some reason. – busybear Mar 07 '19 at 21:56
  • The [issue you say that makes this question not a duplicate](https://stackoverflow.com/questions/55011559/object-list-permutations-are-not-independent-from-one-another-in-python) -- that modifying object properties inside of a loop causes references to those objects to reflect the changed values -- is not present in the sample code you've provided, since you are not modifying the objects you are permuting. I put together a code pen and ran your above code. The issue does not reproduce: https://trinket.io/python/0a90c10c28 – Conspicuous Compiler Mar 08 '19 at 22:51
  • (This is to say, I suspect you have simplified the code you are showing too much and are leaving out a critical portion of the original code which is causing the issue you are observing.) – Conspicuous Compiler Mar 08 '19 at 22:52

0 Answers0