0
votes

Lets say I have a recursive function that creates lists within lists. It return something along the lines of:

['a', ['b', ['c', ['d', []]]], 'z', []]

Lets call this list LIST1

Then I have a function that takes that list, and cleans it up for me, essentially removing the z.Lets call this list LIST2

[a,b,c,d]

What I can do, is call my first function and receive my list, and then(while in the python shell) call my cleanup function on LIST1 to convert it to LIST2. What I'd like to do is have cleanup operate as soon as LIST1 is returned, essentially having cleanup operate within my list generator function.

I'm puzzled on how I'm supposed to call a function that changes the result of a recursive function without screwing up the recursive function.

I don't want to go into specifics of my code, since it's fairly complicated and heavily nested, but ask questions if you'd like me to clarify.

If it helps to visualize a problem, imagine it in simpler terms. I have a function that returns a value, I want another function to operate on that value, but within the first function.

Cheers,

3

3 Answers

1
votes

Is this what you were trying to do ?

import collections

result = ['a', ['b', ['c', ['d', []]]], 'z', []]

def get_result() :
    for r in result :
        yield r


def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el


def remove_z(l) :
    for i in l :
        if i != 'z' :
            yield i

print [ l for l in remove_z(flatten(get_result()))]

And the result is

['a', 'b', 'c', 'd']

The 'flatten' function comes from here : https://stackoverflow.com/a/2158532/16718

0
votes

I might be missing something, but why not just call the cleanup function on the final result of the recursive function? eg

result = cleanup(recursive())
0
votes

Unless you give more details on the recursive function and the cleanup function, it would be difficult to address your issues

Nevertheless, I devised a trivial example which may be similar to what you are currently doing. As you would see, as @Daniel has mentioned, nesting the calls does works the way it should be

Here is the example

Given

>>> def Wind(p):
    if not p:
        return []
    return [p[:1] + Wind(p[1:-1])+p[-1:]]

>>> Wind(range(1,10))
[[1, [2, [3, [4, [5, 5], 6], 7], 8], 9]]

and

>>> def UnWind(p):
    if not p:
        return []
    return p[:1] + UnWind(p[1:-1][0])+p[-1:]

so as you would see the result of UnWind after Wind is working quite well.

>>> UnWind(Wind(range(1,10))[0])
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9]