2012-12-22 92 views
8

可能重複:
Power set and Cartesian Product of a set python的Python itertools排列如何包括重複字符

使用Python和itertools.permutations()我想與重複字符接收並輸出置換。例如,下面我的函數和它的當前輸出。

def perm(n,i): 
    b = 0 
    while b < n: 
     n= n -1 
     from itertools import permutations as p 
     file.write('\n'.join([''.join(item) for item in p(i,n)])) 
perm(4,'0123') 

輸出爲:

012 
013 
021 
023 
031 
032 
102 
103 
120 
123 
130 
132 
201 
203 
210 
213 
230 
231 
301 
302 
310 
312 
320 
321..... 

我怎麼會得到像112或222的輸出?

從我所瞭解的組合不是順序排列的位置。我正在尋找的是找到所有組合,然後每個組合的每個排列組合。這可能嗎?

+1

爲什麼每次在循環中導入'permutations'?爲什麼'''延長線?你可以至少清理一下.. –

回答

18

你根本不需要排列組合。你想要笛卡爾產品:

import itertools 

def perm(n, seq): 
    for p in itertools.product(seq, repeat=n): 
     file.write("".join(p)) 
     file.write("\n") 

perm(4, "0123") 
3

你似乎在尋找的是Cartesian product,而不是一個由itertools提供的排列組合。

您可能會熟悉置換,組合,替換組合和替換以及笛卡爾產品之間的區別,以決定哪種方式最適合您的應用程序,但有可能您正在尋找其他選項。

+0

我也想過了一秒鐘,但是OP似乎想要'012'和'102' - 或者至少他沒有在他的列表中評論它 - 這種情況下他可能是在'itertools.product'之後。 – DSM

+0

是的,我認爲你是對的。我會編輯。 – acjay