简体   繁体   中英

Changing recursive function to iterative function in Python

I read that you can turn any recursive function into an iterative function. I have an iterative function to obtain values from the nested list shown here:

filled_list = [1,2,3,[1,2,3,[1,2,3,[1,2,3,4]]]]

Recursive Function:

def recursive_list(value, count):
    x, _, _, _d = value
    if not count%2:
        yield x
    yield from ([] if not isinstance(_d, list) else recursive_list(_d, count+2))
x = recursive_list(filled_list, 0)
print(list(x), "Parsing a list recursively.")

Output: [1, 1, 1, 1] Parsing a list recursively.

I am trying to turn this into an iterative function. Here is what I have so far. I am stuck and don't understand how to iterate through each nested list until I reach the end. The output should be the same as the recursive function.

def iterative_list(value):
    value_list = []
    for a in value:
        for _d in value:
            a, _, _, _d = value
            y, _, _, _d = _d
            value_list.append(a)
            value_list.append(y)
    return value_list
z = iterative_list(filled_list)
print(z, "Parsing a list iteratively.")

Assuming your input will always follow the same pattern ie three integers, then a list, you can simply use a while loop:

def get_first(d): 
  while isinstance(d[-1], list):
    a, *_, d = d
    yield a
  yield d[0]

print(list(get_first([1,2,3,[1,2,3,[1,2,3,[1,2,3,4]]]])))

Output:

[1, 1, 1, 1]

Timings:

import time

def timeit(f):
  _start = time.time()
  _ = list(f([1,2,3,[1,2,3,[1,2,3,[1,2,3,4]]]]))
  print(f'{f.__name__} finished in {time.time()-_start} seconds')

@timeit
def get_first_iterative(d): 
  while isinstance(d[-1], list):
    a, *_, d = d
    yield a
  yield d[0]

@timeit
def get_first_recursive(d):
  def recursive_list(value):
     x, _, _, _d = value
     yield x
     yield from ([] if not isinstance(_d, list) else recursive_list(_d))
  return recursive_list(d)

Output:

get_first_iterative finished in 2.7894973754882812e-05 seconds
get_first_recursive finished in 1.7881393432617188e-05 seconds

While it appears from the timing above that the recursive solution is faster than the iterative solution, this is not the case, as a plot of the timings of each solution over data up to a depth of 100 reveals:

在此处输入图片说明

The source code for the plot above can be found here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM