2017-12-09 23 views
0

私がどのように見えるのリストがあります:すべての可能な組み合わせは決して同じ

A 
B 
C 
D 
E 
F 
G 

は、どのように私は3桁のためのすべての組み合わせを見つけるために、この問題を解決します。同じ文字を同じ行に使用することはできません。

ABC 
ABD 
ABE 
ABF 
ABG 
AGB 

例えば、何かのように...:

x = ['a','b','c','d','e'] 
n = 3 
import itertools 
aa = [list(comb) for i in range(1, n+2) for comb in itertools.combinations(x, i)] 
print(aa) 

これは、所望の入力を与えるものではありません:

[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c' 
+0

私はあなたが近くにいると思います。私はあなたが望む出力が何であるかを100%理解しているわけではありません。 itertools.combinations(x、i)] '' 'で櫛の範囲(3、4)のiに' '' aa = [list(comb)を使って '' '[['a'、 'b' 、['a'、 'c'、 'd']、['a'、 'b'、 'e']、['a' a、d、e、b、c、d、b、c、 – Martin

答えて

1

ザ・Python標準ライブラリitertoolsは、すでにあなたが実装しようとしている機能があります。また、あなたのコード(funnily)でそれを使用しています。

itertools.combinations(a,3)は、すべての3つの組み合わせを返します。これを「リストのリスト」に変換するには、.extend()を次のように使用する必要があります。

x = ['a','b','c','d','e'] 
n = 3 
import itertools 
permutations = [] 
combinations = [] 
combinations.extend(itertools.combinations(x,n)) 
permutations.extend(itertools.permutations(x,n)) 

print("Permutations;", permutations) 
print("\n") 
print("Combinations;", combinations) 

また、私はあなたが "Combination, Permutation Difference" で検索することをお勧め。あなたの質問から私が理解したように。順列はあなたが望むものです。 (。あなたは私が共有コードを実行した場合、あなたはeasliy違いを理解します)

0

は、溶液プロセスがどのように機能するかを理解するには、以下試してください。

# get all combinations of n items from given list 
def getCombinations(items, n): 
    if len(items) < n: return [] # need more items than are remaining 
    if n == 0: return [''] # need no more items, return the combination of no items 

    [fst, *rst] = items 

    # all combinations including the first item in the list 
    including = [fst + comb for comb in getCombinations(rst, n-1)] 

    # all combinations excluding the first item in the list 
    excluding = getCombinations(rst, n) 

    both = including + excluding 
    return both 

x = ['a','b','c','d','e'] 
n = 3 
print(getCombinations(x, n)) 
# ['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde'] 
+0

並べ替えはすべて一意ですか?はい、 –

+0

これは組み合わせを生成しますが、順列は生成しません。すなわち、「abc」を含み、「bac」は含まない。与えられたリスト中の要素は一意であると仮定します。つまり、 '['a'、 'a'、 'b']'を与えると、2つの 'ab 'が得られます。 –

+0

私は少し違いが分かりません。 permutationsは同じものとのより多くの可能な組み合わせを与えるように思われる? –

0

組み合わせを文字列ではないリスト、そうで動作します最初に使用して、文字列にそれを回す必要があります。''.join(x)

from itertools import combinations 
x = ['a', 'b', 'c', 'd', 'e'] 
n = 3 
aa = combinations(''.join(x), n) 
for comb in aa: 
    print(''.join(comb)) 

OUTPUT

abc 
abd 
abe 
acd 
ace 
ade 
bcd 
bce 
bde 
cde 

または1ライナーとして:

[''.join(comb) for comb in combinations(''.join(x), n)] 
関連する問題