简体   繁体   中英

python permutations of list backtracking

I need to write a python program that prints in ascending order all permutation of list of numbers. I have to write two programs. One with repeat and one without repeat. For example: list is [1,1,3] so first function output will be:

1,1,3
1,3,1
3,1,1

and second func output will be:

1,1,3
1,1,3
1,3,1
1,3,1
3,1,1
3,1,1

right now I wrote this code but I have trouble with the Asc order:

def perm1 (mylist, newlist):

    if len(mylist)==0:
        print ','.join(map(str,newlist))
    for i in range (0, len(mylist)):
        newlist.append(mylist.pop(i))
        perm1(mylist, newlist)
        mylist.insert(i, newlist.pop())

Any help would be appreciated

itertools.permutations() would be perfect for this! You could use it like this:

from itertools import permutations

def perm1(my_list):
    return " ".join(",".join((str(si) for si in i)) for i in sorted(p(my_list))[::-1])

What permutations is is a generator. This yields every single permutations, but some will be equivalent. It is in ascending order, as sorted gives the permutations from lowest to highest and [::-1] reverses it. For descending order, remove the splice ( [::-1] ). One without duplicates can make use of sets and the fact that {0, 5, 6, 7} == {0, 7, 7, 5, 6, 0} .

from itertools import permutations

def perm2(my_list):
    return " ".join(",".join((str(si) for si in i)) for i in reversed(sorted(set(p(my_list)))))

This shows a different way to reverse, using the reversed function, but is functionally the same.

You can make a function that takes (optional) ascending and keep_duplicates parameter will return in ascending order if ascending is True else in descending for ascending and keep_duplicates if True.

from itertools import permutations as p

def perm3(my_list, keep_duplicates=True, ascending=True):
    splice = -2 * reverse + 1 # -1 if True else 1
    if keep_duplicates:
        return " ".join(",".join((str(si) for si in i)) for i in sorted(p(my_list))[::splice])
    return " ".join(",".join((str(si) for si in i)) for i in sorted(set(p(my_list)))[::splice])

Have a look at: https://docs.python.org/2/library/itertools.html#itertools.product

Add import:

from  itertools  import permutations

Repeatable permutation:

aux = [1,1,3]
#Repeatable permutations
for p in sorted(permutations(aux)):
    print p

And for no repeatable:

aux = [1,1,3]
listunique=[]
#No repeatable permutations 
for p in sorted(permutations(aux)):
    if p not in listunique:
        listunique.append(p)

for i in listunique:
    print i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM