6626070
2997924

MATH02, Permutation and combination

Back to the previous page
List of posts to read before reading this article


Contents


Permutation

Method 1 : by Built-in function

def permute(arr):
    result = [arr[:]]
    c = [0] * len(arr)
    i = 0
    while i < len(arr):
        if c[i] < i:
            if i % 2 == 0:
                arr[0], arr[i] = arr[i], arr[0]
            else:
                arr[c[i]], arr[i] = arr[i], arr[c[i]]
            result.append(arr[:])
            c[i] += 1
            i = 0
        else:
            c[i] = 0
            i += 1
    return result




Method 2 : by itertools module

import itertools

pool = ['A', 'B', 'C']
print(list(map(''.join, itertools.permutations(pool, r=3)))) # progression through 3 elements
print(list(map(''.join, itertools.permutations(pool, r=2)))) # progression through 2 elements
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
['AB', 'AC', 'BA', 'BC', 'CA', 'CB']





Combination

import itertools

pool = ['A', 'B', 'C']
print(list(map(''.join, itertools.combinations(pool, r=3)))) # progression through 3 elements
print(list(map(''.join, itertools.combinations(pool, r=2)))) # progression through 2 elements
['ABC']
['AB', 'AC', 'BC']





List of posts followed by this article


Reference