Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I find source code for itertools.combinations() function

Tags:

I'm trying to find a way to write a combination function. Where can I find it?

like image 265
Dhananjaya Avatar asked Apr 20 '11 13:04

Dhananjaya


People also ask

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

Using recursion. 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.

How do you find possible combinations in Python?

To calculate the combinations of a dictionary in Python, use the itertools. combinations() method. The combinations() method takes a dictionary as an argument and returns all the possible combinations of the dictionary elements.

What is combinations in Itertools?

itertools. combinations (iterable, r) Return r length subsequences of elements from the input iterable. The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.


2 Answers

The actual source code is written in C and can be found in the file itertoolsmodule.c.

like image 140
Sven Marnach Avatar answered Nov 09 '22 00:11

Sven Marnach


See in the documentation of itertools.combinations. There is an equivalent code for this function:

def combinations(iterable, r):     # combinations('ABCD', 2) --> AB AC AD BC BD CD     # combinations(range(4), 3) --> 012 013 023 123     pool = tuple(iterable)     n = len(pool)     if r > n:         return     indices = range(r)     yield tuple(pool[i] for i in indices)     while True:         for i in reversed(range(r)):             if indices[i] != i + n - r:                 break         else:             return         indices[i] += 1         for j in range(i+1, r):             indices[j] = indices[j-1] + 1         yield tuple(pool[i] for i in indices) 
like image 38
eumiro Avatar answered Nov 08 '22 23:11

eumiro