Search code examples
pythonpython-3.xpermutation

Write permutation to text file, keeping only unique permutations


I would like to write the unique permutations to a text file. I want only the unique version. My code is as follows:

def permute(lst,f=0):
    if f>=len(lst):
        print(lst)
        return
    for s in range(f, len(lst)):
        lst[f],lst[s] = lst[s],lst[f]
        permute(lst,f+1)
        lst[f],lst[s] = lst[s],lst[f]
        
r=permute(['Cat',
'Dog',
'Bird',
'Rabbit'])

f = open("Permutation_File.txt", "w")
f.write(r)
f.write('\n')
f.close()

Out put looks like this:

['Cat', 'Dog', 'Bird', 'Rabbit']
['Cat', 'Dog', 'Rabbit', 'Bird']
['Cat', 'Bird', 'Dog', 'Rabbit']
['Cat', 'Bird', 'Rabbit', 'Dog']
['Cat', 'Rabbit', 'Bird', 'Dog']
['Cat', 'Rabbit', 'Dog', 'Bird']
['Dog', 'Cat', 'Bird', 'Rabbit']
['Dog', 'Cat', 'Rabbit', 'Bird']
['Dog', 'Bird', 'Cat', 'Rabbit']
['Dog', 'Bird', 'Rabbit', 'Cat']
['Dog', 'Rabbit', 'Bird', 'Cat']
['Dog', 'Rabbit', 'Cat', 'Bird']
['Bird', 'Dog', 'Cat', 'Rabbit']
['Bird', 'Dog', 'Rabbit', 'Cat']
['Bird', 'Cat', 'Dog', 'Rabbit']
['Bird', 'Cat', 'Rabbit', 'Dog']
['Bird', 'Rabbit', 'Cat', 'Dog']
['Bird', 'Rabbit', 'Dog', 'Cat']
['Rabbit', 'Dog', 'Bird', 'Cat']
['Rabbit', 'Dog', 'Cat', 'Bird']
['Rabbit', 'Bird', 'Dog', 'Cat']
['Rabbit', 'Bird', 'Cat', 'Dog']
['Rabbit', 'Cat', 'Bird', 'Dog']
['Rabbit', 'Cat', 'Dog', 'Bird']

How to go about writing a text file that has only unique permutations?

Would like to see

['Cat', 'Dog', 'Rabbit', 'Bird']
['Dog', 'Cat', 'Bird', 'Rabbit']
['Bird', 'Dog', 'Cat', 'Rabbit']
['Rabbit', 'Dog', 'Bird', 'Cat']

I know with only 4 strings it's hard to visualize, but I have 36 strings in my set and that comes to well over a million variations.


Solution

  • It doesn't seem that you want to generate all permutations at all, you can calculate what you want by just 'rolling' the list:

    lst =  ['Cat', 'Dog', 'Bird', 'Rabbit']
    [lst[i:]+lst[:i] for i, _ in enumerate(lst)]
    

    Output:

    [['Cat', 'Dog', 'Bird', 'Rabbit'],
     ['Dog', 'Bird', 'Rabbit', 'Cat'],
     ['Bird', 'Rabbit', 'Cat', 'Dog'],
     ['Rabbit', 'Cat', 'Dog', 'Bird']]