counting using variable length string as base

Graeme Glass graemeglass at gmail.com
Mon Mar 31 08:30:00 EDT 2008


On Mar 27, 11:01 am, Peter Otten <__pete... at web.de> wrote:
> Grimsqueaker wrote:
> > That seems to give me the items in the list back in an iterator. Am I
> > using it incorrectly?
>
> With Dan's functions in cartesian.py you can do the following:
>
> >>> from cartesian import *
> >>> def count(digits):
>
> ...     args = []
> ...     while 1:
> ...             args.append(digits)
> ...             for n in string_cartesian_product(*args):
> ...                     yield n
> ...>>> from itertools import islice
> >>> print " ".join(islice(count("abc"), 30))
>
> a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab
> bac bba bbb bbc bca bcb bcc
>
> Peter

Here is a cool solution we came up with during a little interactive
session at our local meet up.
(http://www.python.org.za/pugs/cape-town/cape-town)

s = 'abcdef'
["".join([s[j] for j in range(len(s)) if x & (1 << j)]) for x in
range(1,2**len(s)) ]
http://groups.google.com/group/ctpug/browse_thread/thread/986aab83f9782f6c

Regards,

Graeme




More information about the Python-list mailing list