All possible combinations for 3 digits of list never the same

前端 未结 3 673
温柔的废话
温柔的废话 2021-01-17 01:57

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

3条回答
  •  再見小時候
    2021-01-17 02:26

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

提交回复
热议问题