Function combinations(iterable, r)


Was trying to find out how to implement the coding to get all the combinations that I could get from 4 items.

Had searched through and found that in python there is such a function (itertools.combinations) for this purpose but when browse through the IA forum and seems to get the impression that the itertools library would not be imported.

Nevertheless, had tried out as follows from the python org ( and it didnt work as i kept getting the message “generator object at 0xa”
"generator object at 0xb " instead of what is to be expected "AB AC AD BC BD CD ".

Wonder what is missing or need to be corrected ?

Thank you

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:
indices = range®
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range®):
if indices[i] != i + n - r:
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)

print combinations(‘ABCD’, 2)
abc = combinations(‘ABCD’, 2)
print abc

Could you please print your code in a code field? Like this, the indentation is lost, which is very important for Python.

That said, the output shows you’re getting back a generator object. A generator can’t be printed, as nothing is calculated yet. To print from a generator, you should loop through it, or f.e. cast it to a list and let the list creator loop throug it.

try print list(combinations'ABCD', 2)) instead

Thanks a lot , it works

beg your pardon for the lost in the indentation and i know it is important for python but sorry to ask where is the code field?

Either use backticks, or click on the “preformatted text” button.

Noted with great Thanks