combinations_from_relations

iteration_utilities.combinations_from_relations(dictionary, r)

Yield combinations where only one item (or None) of each equivalence class is present.

Parameters:

dictionary : dict with iterable values or convertible to one.

A dictionary defining the equivalence classes, each key should contain all equivalent items as it’s value.

Warning

Each value in the dictionary must be iterable.

Note

If the dictionary isn’t ordered then the order in the combinations and their order of appearance is not-deterministic.

Note

If the dictionary isn’t dict-like it will be converted to an collections.OrderedDict.

r : int or None, optional

The number of combinations, if None it defaults to the length of the dictionary.

Returns:

combinations : generator

The combinations from the dictionary.

Examples

In general the collections.OrderedDict should be used to call the function. But it will also be automatically converted to one if one inserts an iterable that is convertible to a dict:

>>> from iteration_utilities import combinations_from_relations

>>> classes = [('a', [1, 2]), ('b', [3, 4]), ('c', [5, 6])]
>>> for comb in combinations_from_relations(classes, 2):
...     print(comb)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(1, 5)
(1, 6)
(2, 5)
(2, 6)
(3, 5)
(3, 6)
(4, 5)
(4, 6)

This is equivalent to creating the collections.OrderedDict manually:

>>> from collections import OrderedDict
>>> odct = OrderedDict(classes)
>>> for comb in combinations_from_relations(odct, 3):
...     print(comb)
(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)