1

I made a tree data structure and a function which gives out all its leaves, but the recursive algorithm never seems to work for any of the child nodes. The function gets called once using the root node

def get_files(self, initials):
    for child in self.children:
        name = initials + os.sep + child.name
        if child.children == []:
            yield name
        else:
            child.get_files(name)

full class: https://pastebin.com/4eukaVWx

J. Doe
  • 43
  • 2
  • 9

2 Answers2

3
    if child.children == []:
        yield name
    else:
        child.get_files(name)

Here you're yielding only in the if. In the other branch, the data is lost. You need to yield the elements returned by child.get_files(name). I'd do:

    if not child.children:
        yield name
    else:
        yield from child.get_files(name)

yield from is available in "recent" python versions. An alternative for older versions is a loop:

for item in child.get_files(name):
   yield item

(a similar issue happens a lot with functions: Why does my function return None?)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • actually the program is working fine normally but the condition i have described happens only in a unittest – J. Doe Aug 08 '18 at 20:00
  • don't quite get you on that, is this know behaviour? why does it seem to be happening like that? – J. Doe Aug 08 '18 at 20:03
  • @J.Doe I notice in your pastebin you are doing a lot of printing. I would actually suggest removing all of the `print`s, and just yielding values. I suspect that you think this program works better than it does because it is printing values that don't actually make it back to the caller. – Patrick Haugh Aug 08 '18 at 20:06
  • @PatrickHaugh the prints were just for debugging the problem i was facing in the question – J. Doe Aug 08 '18 at 20:08
  • I must admit it's not trivial to comprehend. But in recursive algorithms, the results must not be ignored, function or generator, it doesn't matter. recursion+generator that combined complexity gives headaches, you're right. – Jean-François Fabre Aug 08 '18 at 20:09
0

Not a solution but an observation: I guess you are printing something in the pastebin code and you trimmed down the print statement just to post a mve on the question. It works completely fine without the print statements but as soon as you put a single print statement in the method, the recursion stops happening.

Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29
  • I can verify that! Can you explain the theory behind it? – J. Doe Aug 08 '18 at 20:26
  • printing is not returning. The code executes but data doesn't go upstream to the caller. But it's not possible that adding a print makes the code fail... unless tests are scanning standard output. – Jean-François Fabre Aug 08 '18 at 20:42