Alex
Alex

Reputation: 1375

Recursive searching through directories structure

I created recursive function for finding directory with ID I need to use:

def find_id(content, id):
    for drive_obj in content:
        print('Got {}'.format(drive_obj.id))
        if drive_obj.id == id:
            print('Find id in {}'.format(drive_obj.id))
            return drive_obj
        elif type(drive_obj) == Directory and drive_obj.children:
            print('{} has children'.format(drive_obj.id))
            return find_id(drive_obj.children, id)

After running test(find_id(example_structure, 'c')) on this directories structure:

dir_a
-----dir_b
----------file_e
-----dir_c
-----dir_d
dir_f

Logs:
    Got a
    a has children
    Got b
    b has children
    Got e

i got a problem, because function after finding file with id = e doesn't examine next dir_c. It just return None instead of continue the loop. Something wrong with my function or my understanding of it/recursive functions at all?

Upvotes: 0

Views: 32

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60944

The problem is because you return find_id(drive_obj.children, id) even if you don't find the directory you're looking for:

def find_id(content, id):
    for drive_obj in content:
        print('Got {}'.format(drive_obj.id))
        if drive_obj.id == id:
            print('Find id in {}'.format(drive_obj.id))
            return drive_obj
        elif type(drive_obj) == Directory and drive_obj.children:
            print('{} has children'.format(drive_obj.id))
            result = find_id(drive_obj.children, id)  # Now if find_id returns None, we don't stop
            if result:  # result is not None if your objects can be falsy
                return result

You want find_id to return None if it doesn't find anything, and you want to avoid bubbling those None results up to the caller.

Upvotes: 1

Related Questions