Click here to Skip to main content
15,923,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to understand the combination function in itertools, but I'm stuck with one of the loops. Beyond the else statement, I can't follow what's going on. Do the "indices[i] += 1", and for loop fall into the return function?

Also, why does the code need to stipulate the j + 1 = j-1+1?

Python
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:
	    print("oops")
    indices = list(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)


What I have tried:

I understand return and else statements overall, and I've worked through the code up until this point. I'm just looking for some help here.
Posted
Updated 30-Oct-16 22:26pm

1 solution

A good explanation can be found at The Python yield keyword explained | Python Tips[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900