简体   繁体   中英

All possible combinations for 3 digits of list never the same

I have a list that looks like:

A
B
C
D
E
F
G

How do I solve this to find all combinations for 3 digits. The same letter cannot be used in same row.

ABC
ABD
ABE
ABF
ABG
AGB

Eg something like...:

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)

This does not give desired input:

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

The Python Standard Library itertools already has the functionality you are trying to implement. Also you are using it in your code (funnily).

itertools.combinations(a,3) returns all 3-combinations of the a. To convert that to "list of list" you should use .extend() as follows;

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)

Additionally, I suggest you to search on " Combination, Permutation Difference ". As I understood from your question; permutation is what you want. (If you run the code I shared, you will understand the difference easliy.)

To understand how the solution process works, try the following:

# 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']

combinations works on strings not lists, so you should first turn it into a string using: ''.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

Or as a one-liner:

[''.join(comb) for comb in combinations(''.join(x), n)]

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