ABC
ABC

Reputation: 47

python lists numbers

I need to print all the lists of numbers in python.

so far I wrote this:

def lists(listNum, i):    

    if i == len(listNum) - 1:
       print listNum    
    else:    
        for j in range(i, len(listNum)):
            listNum[i], listNum[j] = listNum[j], listNum[i]    
            lists(listNum, i + 1)    
            listNum[i], listNum[j] = listNum[j], listNum[i]     

lists([1, 2, 3], 0)

how can I print every list only once? If the list has duplicate elements, e.g. 1,1,2, it will print the same sequence multiple times. how can I prevent this?

I don't know what to do. someone has another idea how to prevent the printing twice?

Upvotes: 2

Views: 248

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

Keep track of what has been added:

def permute(a, i, seen=set()):
    if i == len(a):
        if tuple(a) not in seen:
            seen.add(tuple(a))
            print(a)
    else:
        for j in xrange(i,len(a)):
            a[i], a[j] = a[j], a[i]
            permute(a, i + 1,seen)
            a[i], a[j] = a[j], a[i]

print(permute([1, 1, 3], 0))
[1, 1, 3]
[1, 3, 1]
[3, 1, 1]

Upvotes: 2

Related Questions