counting using variable length string as base

rootkill lcordier at gmail.com
Tue Apr 1 05:15:48 EDT 2008


On Mar 27, 8: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?
>
> Thanks
> Daniel Browne

Since you didn't ask for the smallest solution I'll opt for the
clearest one ;)

I'll use the very usefull baseconvert,
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286

def baseconvert(number, fromdigits, todigits):
    if str(number)[0] == '-':
        number = str(number)[1:]
        neg = 1
    else:
        neg = 0

    # make an integer out of the number
    x = long(0)
    for digit in str(number):
       x = x * len(fromdigits) + fromdigits.index(digit)

    # create the result in base 'len(todigits)'
    res = ''
    if x == 0:
        res = todigits[0]

    while x > 0:
        digit = x % len(todigits)
        res = todigits[digit] + res
        x /= len(todigits)

    if neg:
        res = '-' + res

    return res

BASE10 = '0123456789'
s = 'abcdef'
n = len(s)

for i in xrange(n**n):
    print baseconvert(str(i), BASE10, s)

You can also convert back, baseconvert('abaa', s, BASE10).
Hope it helps.

Regards, Louis.



More information about the Python-list mailing list