Вопрос

I've done this algorithm before, in school, but I've forgotten how to do it. Basically I want to return a result that are strings like 'a[0]', 'a[0].a[0]' ...

length = range(0,2) #length = 2
depth = range(0,3)  #depth = 3

for i in length:
    for k in depth:
        …   print each permutation

RESULT

a[0]
a[0].a[0]
a[0].a[1]
a[0].a[0].a[0]
a[0].a[0].a[1]
a[0].a[1].a[0]
a[0].a[1].a[1]
a[1]
a[1].a[0]
a[1].a[1]
a[1].a[0].a[0]
a[1].a[0].a[1]
a[1].a[1].a[0]
a[1].a[1].a[1]
Это было полезно?

Решение

Changing a bit the ordering of the output, so that it is the same on all levels:

def thing (length, depth, prefix = None):
    if not depth: return
    if not prefix: prefix = []
    for l in range (length):
        r = prefix + ['a[{}]'.format (l) ]
        yield '.'.join (r)
        for r in thing (length, depth - 1, r):
            yield r

for x in thing (2, 3): print (x)

Output is:

a[0]
a[0].a[0]
a[0].a[0].a[0]
a[0].a[0].a[1]
a[0].a[1]
a[0].a[1].a[0]
a[0].a[1].a[1]
a[1]
a[1].a[0]
a[1].a[0].a[0]
a[1].a[0].a[1]
a[1].a[1]
a[1].a[1].a[0]
a[1].a[1].a[1]

Другие советы

An alternative approach; as Hyperboreus points out, the key is realizing that the ordering of the first-elements does not match that of the following elements; so I handle them separately.

from itertools import product

def item_fmt(i):
    return "a[{}]".format(repr(i))

def make_result(*args):
    return ".".join(item_fmt(arg) for arg in args)

def main():
    items    = [0, 1]
    maxdepth = 3

    for first in items:              # in order by first-item
        print(make_result(first))    # show first-item-only
        for depth in range(1, maxdepth):                # in order by depth
            for combo in product(items, repeat=depth):  # generate all combinations of given depth
                print(make_result(first, *combo))

if __name__=="__main__":
    main()

results in

a[0]
a[0].a[0]
a[0].a[1]
a[0].a[0].a[0]
a[0].a[0].a[1]
a[0].a[1].a[0]
a[0].a[1].a[1]
a[1]
a[1].a[0]
a[1].a[1]
a[1].a[0].a[0]
a[1].a[0].a[1]
a[1].a[1].a[0]
a[1].a[1].a[1]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top