vary number of loops

Mensanator mensanator at aol.com
Wed Apr 16 13:42:40 EDT 2008


On Apr 16, 8:31 am, nullgr... at gmail.com wrote:
> Hi everyone,
>
> I'm new to Python and the notion of lambda, and I'm trying to write a
> function that would have a varying number of nested for loops
> depending on parameter n. This just smells like a job for lambda for
> me, but I can't figure out how to do it. Any hint?
>
> For example, for n=2, I want the function to look something like:
>
> def foo(2)
>    generate 2 sets of elements A, B
>    # mix elements by:
>    for a_elt in A
>       for b_elt in B
>          form all combinations of them
>
> If n=3, I want to have 3 sets of elements and mix them up using 3 for
> loops.
>
> Any help is greatly appreciated,
>
> nullgraph


There's always the stupid way:

def ooloop6(a, n, perm=True, repl=True):
    if (not repl) and (n>len(a)): return
    r0 = range(n)
    r1 = r0[1:]
    if perm and repl:                          # permutations with
replacement
        v = ','.join(['c%s' % i for i in r0])
        f = ' '.join(['for c%s in a' % i for i in r0])
        e = ''.join(["p = [''.join((",v,")) ",f,"]"])
        exec e
        return p
    if (not perm) and repl:                    # combinations with
replacement
        v = ','.join(['c%s' % i for i in r0])
        f = ' '.join(['for c%s in a' % i for i in r0])
        i = ' and '.join(['(c%s>=c%s)' % (j,j-1) for j in r1])
        e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
        exec e
        return p
    if perm and (not repl):                    # permutaions without
replacement
        v = ','.join(['c%s' % i for i in r0])
        f = ' '.join(['for c%s in a' % i for i in r0])
        i = ' and '.join([' and '.join(['(c%s!=c%s)' % (j,k) for k in
range(j)]) for j in r1])
        e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
        exec e
        return p
    if (not perm) and (not repl):              # combinations without
replacement
        v = ','.join(['c%s' % i for i in r0])
        f = ' '.join(['for c%s in a' % i for i in r0])
        i = ' and '.join(['(c%s>c%s)' % (j,j-1) for j in r1])
        e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
        exec e
        print '\n\n',e,'\n\n'
        return p

a = 'abcdefghij'
n = 6

# for lotto use Combinations without Replacement
p = ooloop6(a,n,False, False)
##################################################################

Here's the code that gets executed:

## p = [''.join((c0,c1,c2,c3,c4,c5)) for c0 in a
## for c1 in a for c2 in a for c3 in a for c4 in a
## for c5 in a if (c1>c0) and (c2>c1) and (c3>c2)
## and (c4>c3) and (c5>c4)]



More information about the Python-list mailing list