Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While generating all possible combinations itertools.combinations_with_replacement() vs itertools.product()?

While writing a program that finds all the different combos for a list, I found a lot of threads about using intertools.product() instead of intertools.combinations_with_replacement(), as I have been doing. No one explained why you should use intertools.product. I would love to know how this affects my program output.

like image 375
Torkoal Avatar asked Jan 20 '14 00:01

Torkoal


People also ask

How do you get all possible combinations of a list in Python without Itertools?

To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.

What does Itertools combinations return?

What does itertools. combinations() do ? It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order.

How does Itertools combinations work?

itertools.combinations(iterable, r)This tool returns the length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.


1 Answers

From Python documentation

itertools.product(*iterables[, repeat])

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

In other words:

for x, y in itertools.product(A, B):

replaces

for x in A:
    for y in B:
............

EDIT:

  • itertolls.combinations_with_replacement() will take single iterable and produce all possible combinations of its elements of given length;

  • itertools.product() will produce combination of values from several iterables, where element 0 of the resulting tuple is from the first iterable, element 1 - from second, etc.

like image 77
volcano Avatar answered Oct 23 '22 09:10

volcano