I am trying to generate a list of permutations in a loop and print for each iteration with output more than two (or write to lines of a file).
Example input list:
['one', 'two', 'three', 'four']
Required output:
['one', 'two', 'three', 'four']
['two', 'three', 'four']
['one', 'three', 'four']
['one', 'two', 'four']
['one', 'two']
['one', 'three']
['one', 'four']
['two', 'three']
['two', 'four']
['three', 'four']
This is what I've managed so far (very early in my Python life, please excuse):
from itertools import permutations
input = ['one', 'two', 'three', 'four']
def convertTuple(tup):
str = ''.join(tup)
return str
while (len(input) > 1):
permlist = set(permutations(input))
for i in permlist:
print(i)
i = convertTuple(i)
outfile = open("out.txt", "w")
outfile.write(i)
input = input[:-1]
else:
print("End of permutation cycle")
Which outputs:
('two', 'three', 'one', 'four')
('two', 'four', 'one', 'three')
('three', 'two', 'one', 'four')
('four', 'two', 'one', 'three')
('two', 'one', 'three', 'four')
('two', 'one', 'four', 'three')
('three', 'one', 'four', 'two')
('four', 'one', 'three', 'two')
('one', 'two', 'three', 'four')
('one', 'two', 'four', 'three')
('three', 'four', 'one', 'two')
('four', 'three', 'one', 'two')
('two', 'three', 'four', 'one')
('two', 'four', 'three', 'one')
('three', 'two', 'four', 'one')
('three', 'four', 'two', 'one')
('four', 'two', 'three', 'one')
('four', 'three', 'two', 'one')
('three', 'one', 'two', 'four')
('four', 'one', 'two', 'three')
('one', 'four', 'two', 'three')
('one', 'three', 'two', 'four')
('one', 'three', 'four', 'two')
('one', 'four', 'three', 'two')
('two', 'three', 'one')
('three', 'two', 'one')
('three', 'one', 'two')
('one', 'two', 'three')
('one', 'three', 'two')
('two', 'one', 'three')
('two', 'one')
('one', 'two')
End of permutation cycle
I understand I am going wrong with
input = input[:-1]
as it just removes the last value in the original list but I can't work out how to get only unique lists back with different numbers of values in each list...
Am I using the wrong part of itertools? Should I be using combinations or something else?
I am seriously stuck so any help is very much appreciated!
Thanks!