Home > Blockchain >  recursion function recurring too often
recursion function recurring too often

Time:11-07

Relatively early in my python journey and coding in general. I've come across an example question that asks that should flatten a list of lists. Now how many lists of lists exist I wouldn't know. Which leads me to doing my first recursion attempt:

array = [[1,2,3,['a','b','c'],4],'d', [5,6],[7],8,9]
flattened = []

def flattenme (iteritem):
    
    for item in iteritem:
        if isinstance(item, Iterable) or isinstance(item, (str,bytes)):
            flattenme(item)
        else:
            flattened.append(item)

When I run this with

print(f"flatten method: {list(flattenme(array))}")

I get the error:

RecursionError: maximum recursion depth exceeded in comparison

Shouldn't

flattenme(item)

at the last time it's called just return the non-list item? I'm not sure what is going wrong and where my understanding of recursion is failing.

CodePudding user response:

Strings and bytes are iterable. Specifically, strings yield strings of length 1 when iterated over.

This means your code recurses infinitely.

Furthermore, your function doesn't return anything.

Here is my suggestion, which makes flattenme a generator that doesn't split strings:

array = [[1,2,3,['a','b','c'],4],'d', [5,6],[7],8,9]

def flattenme (iteritem):
    for item in iteritem:
        if isinstance(item, Iterable) and not isinstance(item, (str,bytes)):
            yield from flattenme(item)
        else:
            yield item
  • Related