0

So I am exploring the code behind itertools.combinations. In the documentation it gives an "equivelent" as follows:

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)

So let's say I have a list:

sequence = [1,2,3,4,5,6,7,8,9,10] 

and:

r=3

I tried to convert the generator to the list and then print it but I'm getting:

print(list(combinations(sequence,3)))
...
---> 16         indices[i] += 1
 17         for j in range(i+1, r):
 18             indices[j] = indices[j-1] + 1
TypeError: 'range' object does not support item assignment

I am having trouble modifying this to work without causing even more errors. If someone could offer me some guidance on figuring out how to resolve this TypeError I would really appreciate it.

In short I want to know why doing this works but the previous code doesn't:

print(list(itertools.combinations(sequence,3)))
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 2, 7) ...]
feynmanium
  • 159
  • 2
  • 13
  • 3
    You should look at [the 3.x documentation](https://docs.python.org/3/library/itertools.html#itertools.combinations), the version you're trying is for 2.x. Or, as you should have done before asking, search for the error message: http://stackoverflow.com/q/9091044/3001761, http://stackoverflow.com/q/20484195/3001761, http://stackoverflow.com/q/16435607/3001761 – jonrsharpe Mar 20 '17 at 22:59
  • 1
    Specifically, in 3.x, `range` returns a generator rather than a list (as it did in 2.x). The 3.x equivalent forces it into a list first: `indices = list(range(r))`. https://docs.python.org/3/library/itertools.html#itertools.combinations – Peter DeGlopper Mar 20 '17 at 23:02
  • 1
    @PeterDeGlopper: Python 3 `range` does not return a generator. It returns a lazy sequence object. In particular, it's a real sequence, supporting indexing and slicing, and you can iterate over a single `range` object repeatedly. – user2357112 Mar 20 '17 at 23:40
  • Thanks, I was sloppy with that comment. – Peter DeGlopper Mar 21 '17 at 16:07

1 Answers1

0

By modifying the line:

indices = range(r)

to:

indices = list(range(r))

Answered my question. Thank you comments.

feynmanium
  • 159
  • 2
  • 13