0

Is there a method I can utilise that: execute for for n times?

Sorry, it may sounds extremely confusing to you. Here is what I am trying to do:

I have a list:


array = [
    [
        [1, 2],
        [3, 4],
    ],
    [
        [100, 200],
        [300, 400]
    ]
]

I seek for a generator to yields # generator, yields [1, 2], [3, 4], [5, 6], [7, 8] sequentially.

for the example array above, let depth be 2, depth varies in different circumstance.

here is what I have tried so far:


array = [
    [
        [1, 2],
        [3, 4],
    ],
    [
        [100, 200],
        [300, 400]
    ]
]

# set a con, increment by 1 before each `for`
con = 0
depth = 2


def loop(arr):
    global con
    con += 1
    if con == depth:
        for i in arr:
            # the only place to exit the function
            yield i
    else:
        for i in array:
            # nest looping
            yield loop(i)


for ll in loop(array):
    print(ll)


# expected output
# [1, 2]
# [3, 4]
# [5, 6]
# [7, 8]

# however I got
# <generator object loop at 0x7f8cc815ac80>
# <generator object loop at 0x7f8cc818c2e0>

I think the issue is that in nested looping, I could not call loop function after yield

It has confused me all day long, I will be so glad if someone offers some help.


Update

Thanks to @Nick Parsons, for pointing out Can generators be recursive?, I am able to work following out, but I got an recursion exceed error:


array = [
    [
        [1, 2],
        [3, 4],
    ],
    [
        [100, 200],
        [300, 400]
    ]
]

# set a con, increment by 1 before each `for`
con = 0
depth = 2


def loop(arr):
    global con
    con += 1
    if con == depth:
        for i in arr:
            # the only place to exit the function
            yield i
    else:
        for i in array:
            # nest looping
            yield from loop(i)


for ll in loop(array):
    print(ll)


# expected output
# [1, 2]
# [3, 4]
# [5, 6]
# [7, 8]

# however I got
RecursionError: maximum recursion depth exceeded in comparison

Weilory
  • 2,621
  • 19
  • 35
  • Does this answer your question? [Can generators be recursive?](https://stackoverflow.com/questions/38254304/can-generators-be-recursive) – Nick Parsons Sep 24 '20 at 03:24

1 Answers1

1

As pointed out in the proposed duplicate, your problem is that you are using

yield loop(i)

which returns a generator, where you should be using

yield from loop(i)

to yield the values from the recursion.

Note that you can simplify your code and make it flexible to work with nested lists of any depth by checking the type of the list elements passed into the function and recursing if they are lists:

def loop(arr):
    if type(arr[0]) is list:
        for a in arr:
            yield from loop(a)
    else:
        yield arr

for ll in loop(array):
    print(ll)

Output:

[1, 2]
[3, 4]
[100, 200]
[300, 400]
Nick
  • 138,499
  • 22
  • 57
  • 95