generate all combinations of a list (with variable output length)

mark mceahern marknews at mceahern.com
Sat Jun 29 11:41:49 EDT 2002


bokr at oz.net (Bengt Richter) wrote in message news:<afip0i$8c3$0 at 216.39.172.122>...
> Or, implementing your base-5 digits idea, and leaving out '':
> 
>  >>> def adD5r(n):
>  ...     codes='AD$5R' # <=> 01234
>  ...     out = []; m = n
>  ...     while 1:
>  ...         n,d = divmod(n,5)
>  ...         out.append(codes[d])
>  ...         if not n:break
>  ...     out.reverse()
>  ...     return '%d:%s' % (m,''.join(out))
>  ...

Bengt, this is smoov.  I took your code and, using nested scopes, made
a function that returns the equivalent of adD5r for an arbitrary set
of codes:

def make_number_generator(codes):
    def number_generator(n):
        out = []
        m = n
        while 1:
            n, d = divmod(n, len(codes))
            out.append(codes[d])
            if not n:
                break
        out.reverse()
        return '%s' % (''.join(out))
    return number_generator

codes='AD$5R' # <=> 01234
number_generator = make_number_generator(codes)
n = 0
print "%d:%s" % (n, number_generator(n))
n = len(codes) ** 10 - 1
print "%d:%s" % (n, number_generator(n))

Cheers,

// mark



More information about the Python-list mailing list