[Tutor] Calculating and returning possible combinations of elements from a given set

ZUXOXUS zuxoxus at gmail.com
Thu Jul 29 13:52:37 CEST 2010


2010/7/28 Dave Angel <davea at ieee.org>

> ZUXOXUS wrote:
>
>> <snip>
>>
>> My doubt now is whether I can change the way python show the combinations.
>>
>> I mean, here's what python actually does:
>>
>>
>>
>>> for prod in itertools.product('abc', repeat=3):
>>>>>
>>>>>
>>>> print(prod)
>>
>> ('a', 'a', 'a')
>> ('a', 'a', 'b')
>> ('a', 'a', 'c')
>> ('a', 'b', 'a')
>> ('a', 'b', 'b')
>> ('a', 'b', 'c')
>> [...] etc.
>>
>>
>> what if I want the combinations listed in a... well, in a list, kind of
>> like
>> this:
>>
>> ('aaa', 'aab', aac', 'aba', 'abb', 'abc' [...]etc.)
>>
>> can I do that?
>>
>> I have checked how the function works (see below), perhaps I have to just
>> change couple of lines of the code and voilá, the result displayed as I
>> want... But unfortunately I'm too newbie for this, or this is too
>> hardcore:
>>
>> def product(*args, **kwds):
>>    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
>>    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
>>    pools = map(tuple, args) * kwds.get('repeat', 1)
>>    result = [[]]
>>    for pool in pools:
>>        result = [x+[y] for x in result for y in pool]
>>    for prod in result:
>>        yield tuple(prod)
>>
>>
>> Any ideas will be very much appreciated.
>>
>> <snip, double-included history>
>>
> Well itertools.product() already returns an iterator that's equivalent to a
> list of tuples.   You can print that list simply by doing something like:
> print list(itertools.product('abc', repeat=3))
>
> So your question is how you can transform such a list into a list of
> strings instead.
>
> so try each of the following.
>
>
> for prod in itertools.product('abc', repeat=3):
>   print "".join(prod)
>
> print ["".join(prod) for prod in itertools.product('abc', repeat=3)]
>
> DaveA
>
>
***

Hi DaveA, the second option returns exactly the result I wanted:

>>> print(["".join(prod) for prod in itertools.product('abc', repeat=3)])
['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa',
'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac',
'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

Thank you very much.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100729/c720e53c/attachment.html>


More information about the Tutor mailing list