How do I make this function automatic, it clearly has a pattern

Question:

def populate_kids(self, arr, used_Indices):
    for a in self.children:
        a.get_all_jumps(arr, used_Indices)

    for a in self.children:
        for b in a.children:
            b.get_all_jumps(arr, used_Indices)

    for a in self.children:
        for b in a.children:
            for c in b.children:
                c.get_all_jumps(arr, used_Indices)

    for a in self.children:
        for b in a.children:
            for c in b.children:
                for d in c.children:
                    d.get_all_jumps(arr, used_Indices)

How do I make this automatically

I tried recursion it doesn’t seem to work

Asked By: Currency

||

Answers:

This looks like a BFS (breadth-first-search), so something along these lines might work:

def populate_kids(self, arr, used_Indices):
    queue = self.children
    while queue:
        next_queue = []
        for a in queue:
            a.get_all_jumps(arr, used_Indices)
            if a.children:
                next_queue.extend(a.children)
        queue = next_queue

The basic idea is that as you process the queue, you add the next level of items to search to the queue for the next iteration. Eventually you reach the point where there are no more levels, and the search ends.

For a DFS (depth-first search), recursion is easier (I’m assuming the objects in self.children have the same type as self):

def populate_kids(self, arr, used_Indices):
    for a in self.children:
        a.get_all_jumps(arr, used_Indices)
        a.populate_kids(arr, used_Indices)

but the order of traversal will be different (you’ll recurse all the way down to the deepest level before finishing the loop at the current level).

Answered By: Samwise

Use recursion to automate a function that populates data in a tree-like structure. By defining a recursive function that calls itself on each child of a node, the function can handle any pattern of nested children, eliminating the need for repetitive for loops. In this way, all descendants of a node can be processed without explicitly iterating through each level.

    def populate_kids(self, arr, used_Indices):
            for child in self.children:
                self._populate_kids_recursive(child, arr, used_Indices)
        
        def _populate_kids_recursive(self, node, arr, used_Indices):
            node.get_all_jumps(arr, used_Indices)
            for child in node.children:
                self._populate_kids_recursive(child, arr, used_Indices)
Answered By: Mustafa Walid