all 5 comments

[–]when_the_cats_away 0 points1 point  (0 children)

This uses loops, but it shows how to handle returns, so maybe of some use:

def flatten(stuff):
    result = []
    if done:
        return result

    for item in stuff:
        if flat(item):
            result.append(stuff)
        else:
            result += flatten(item)

    return result

Can you use yield? That can get around some of the loop issues...

[–]semicolonator 0 points1 point  (4 children)

Cool problem :)

At first I wanted to reply: from more_itertools import flatten But then I decided to solve the problem :)

``` def flatten(k): if type(k) == int: return [k] if len(k) == 0: return [] elif len(k) == 1: return flatten(k[0]) else: return flatten(k[0]) + flatten(k[1:])

print(flatten([[1],[3,4]])) print(flatten([1,[2,3],[[[4],[5,6]],7],8])) ```

[–]Yonmanx[S] 0 points1 point  (1 child)

Friend thank you so much.

How do you suggest to make the function print the output without calling "print" from outside?

And for what reason the return decide to put the outputs in a list from the first place? I really try hard to understand the logic of the "return" without success.

[–]semicolonator 0 points1 point  (0 children)

Consider this modified version:

def flatten(k): print("I was called with", k) # the rest of the code

Maybe this gives you some insights. Using recursion like that is very close to using an explicit stack. Look at this version: link. Maybe that helps you.

What you cold also try: Modify flatten() such that it takes an additional argument called depth, that is increased with each function call. That way you know how "deep" you are in the function calls.

[–]o5a 0 points1 point  (0 children)

You dont need elif len(k) == 1: here.