views:

120

answers:

4
test = ["a","b","c","d","e"]

def xuniqueCombinations(items, n):
    if n==0: yield []
    else:
        for i in xrange(len(items)-n+1):
            for cc in xuniqueCombinations(items[i+1:],n-1):
                yield [items[i]]+cc

x = xuniqueCombinations(test, 3)
print x

outputs

"generator object xuniqueCombinations at 0x020EBFA8"

I want to see all the combinations that it found. How can i do that?

+3  A: 

This is a generator object. Access it by iterating over it:

for x in xuniqueCombinations:
    print x
leoluk
for x in xuniqueCombinations:TypeError: 'function' object is not iterable
Alex
@Alex You need to call the function: `for x in xuniqueCombinations(test, 3)`. Alternatively just do `print list(xuniqueCombinations(test, 3))`.
Joe Kington
you mean:for x in xuniqueCombinations(test,3):
Alex
A: 

It might be handy to look at the pprint module: http://docs.python.org/library/pprint.html if you're running python 2.7 or more:

from pprint import pprint
pprint(x)
cpf
pprint(x)<generator object xuniqueCombinations at 0x020EBFA8>that is no different...
Alex
+8  A: 

leoluk is right, you need to iterate over it. But here's the correct syntax:

combos = xuniqueCombinations(test, 3)
for x in combos:
    print x

Alternatively, you can convert it to a list first:

combos = list(xuniqueCombinations(test, 3))
print combos
Colin Gislason
A: 
x = list(xuniqueCombinations(test, 3))
print x

convert your generator to list, and print......

Tumbleweed
Don't like this answer without at least a warning about the memory implications.
Triptych
ohh ok, but if someone executes loop over generator object for printing without converting it to list, he can not execute loop over it again without calling that function again as iterator will be exhausted ....
Tumbleweed