I have a list that can have anything from 3 to 10 elements and I need to be able to print out all the permutations of these elements.
The issue that I'm having is that Jython doesn't seem to have any of the python or java ways of doing this (no perm() no yield etc) so I have to rely on using loops.
I've worked out the following works:
for 3 elements I do the following 3 times and that gives all options
list.pop(elements-2) /n list.append
list.pop(elements-3) /n list.append
print
list.pop(elements-2) /n list.append
list.amend
print
for 4 elements I do the same 3 times then I have to do
list.pop(elements-4) /n list.append
then previous loop 3 times then pop(elements-4)
. That is done 4 times.
For 5 elements I have to do the 4 element loop 5 times with a pop(elements-5)
after each loop and so on but I can't conceptualize how to put this all nicely.
Any help would be great as I can't seem to bend any java/python solutions into the right shape.
Ok. After some more research and playing I have come up with the following code:
def findPerms():
myList = [9,2,3,6]
allPerms=[]
elementCount = 0
for i in myList:
elementCount+= 1
for i in range(0,elementCount):
for j in range(1,elementCount):
perm=[]
for k in range(0,elementCount):
perm.append(myList[k])
if allPerms.count(perm) == 0:
print perm
allPerms.append(perm)
h = myList[j]
myList[j]=myList[j-1]
myList[j-1] = h
It works fine for 3 elements but only gives 12 perms for 4 elements and 20 for 5 elements so for e > 3 it is out by a factor of e
Any ideas?