counting using variable length string as base

David Fraser davidf at sjsoft.com
Tue Apr 1 03:55:52 EDT 2008


On Mar 31, 8:18 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Mon, 31 Mar 2008 09:30:00 -0300, Graeme Glass <graemegl... at gmail.com>
> escribió:
>
> > On Mar 27, 11:01 am, Peter Otten <__pete... at web.de> wrote:
> >> 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
>
> > 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)) ]
>
> But it's doesn't generate the right sequence, and a lot of elements are
> missing. For 'abc':
> ['a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
> It lacks ba, bb, ca, cb, cc, all b??, all c?? - see the sequence quoted
> above.

Indeed, the following shold do the trick although it's fairly
inefficient:
n=(len(s)+1) ; z = [''] + list(s) ; all =
sorted(dict.fromkeys("".join(z[(x/(n**j))%n] for j in range(n)) for x
in range(1,n**n)))

Cheers
David



More information about the Python-list mailing list