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) ...]