[英]python permutations of list backtracking
我需要編寫一個Python程序,該程序以升序打印數字列表的所有排列。 我必須編寫兩個程序。 一種重復,一種不重復。 例如:list是[1,1,3],因此第一個函數的輸出將是:
1,1,3
1,3,1
3,1,1
第二個func輸出將是:
1,1,3
1,1,3
1,3,1
1,3,1
3,1,1
3,1,1
現在我寫了這段代碼,但是我對Asc命令有麻煩:
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())
任何幫助,將不勝感激
itertools.permutations()
將是完美的選擇! 您可以這樣使用它:
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])
permutations
是一個生成器。 這將產生每個單個排列,但有些將是等效的。 它以升序排列, sorted
的排列順序從最低到最高, [::-1]
將其反轉。 對於降序,請刪除接頭( [::-1]
)。 沒有重復項的人可以利用sets
和{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)))))
這顯示了使用reversed
功能的另一種反向方式,但功能上相同。
你可以做一個函數,它(可選) ascending
和keep_duplicates
參數將在升序返回,如果上升是降序升序和其他真keep_duplicates
如果真。
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])
看看: https : //docs.python.org/2/library/itertools.html#itertools.product
添加導入:
from itertools import permutations
可重復排列:
aux = [1,1,3]
#Repeatable permutations
for p in sorted(permutations(aux)):
print p
不可重復:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.