Python - Combination Codebook

> Procedural Languages > Python

1 - About

3 - Combination

3.1 - where ordering doesn't matter

3.1.1 - Comprehension

Python - Comprehension (Iteration)

This code can use only numbers. An other processing is needed to apply it to string or symbol.

elementLen = 4
combinationComprehension = [(i,j,k) for i in range(elementLen) for j in range(elementLen) for k in range(elementLen) if i != j and i!=k and j!=k and i<j and j<k]

output:

[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
Advertising

3.1.2 - Itertools

With itertools, all characters are allowed.

from itertools import combinations
myElementList = ['a','b','c','d']
combinationItertool = [x for x in combinations(myElementList,3)]
print(combinationItertool)

output:

[('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]

3.2 - where ordering matter

3.2.1 - Comprehension

Recursive comprehension: Generation of all combinations of element (in myList) over a variable length (in myLength) :

myLength = 3
myList = [0,1]
scalarList = [[i] for i in myList] 
count = 1
while count < (myLength):
    scalarList = [k+[j] for j in myList for k in scalarList]
    count += 1
print(scalarList)
[[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
lang/python/combination.txt · Last modified: 2018/11/21 20:22 by gerardnico