counting using variable length string as base
Dan Bishop
danb_83 at yahoo.com
Thu Mar 27 02:29:29 EDT 2008
On Mar 27, 1:15 am, Grimsqueaker <Grimsqueake... at gmail.com> wrote:
> Hi, I'm fairly new to Python and to this list. I have a problem that
> is driving me insane, sorry if it seems simple to everyone, I've been
> fighting with it for a while. :))
>
> I want to take a variable length string and use it as a base for
> counting, eg. given the string 'abc' the sequence would be:
>
> a
> b
> c
> aa
> ba
> ca
> ab
> bb
> cb
> ...
> ccc
>
> Basically I want to find every possible order of every combination.
> Its easy if you know how many characters there will be in your string
> (use nested for loops), but I am stuck with the variable length
> string. I think I have to use a generator but I'm not sure exactly
> how.
>
> Can anyone give me a pointer in the right direction?
def cartesian_product(*args):
"""Iterates over the Cartesian product of args[0], args[1], ..."""
if not args:
return
elif len(args) == 1:
for item in args[0]:
yield (item,)
else:
for item in args[0]:
for item2 in cartesian_product(*args[1:]):
yield (item,) + item2
def string_cartesian_product(*args):
return (''.join(combo) for combo in cartesian_product(*args))
More information about the Python-list
mailing list