[prev in list] [next in list] [prev in thread] [next in thread]
List: python-list
Subject: Re: counting using variable length string as base
From: Dan Bishop <danb_83 () yahoo ! com>
Date: 2008-03-27 6:29:29
Message-ID: 0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e () s8g2000prg ! googlegroups ! com
[Download RAW message or body]
On Mar 27, 1:15 am, Grimsqueaker <Grimsqueake...@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))
--
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic