Home > Software engineering >  Conting how many times recurion occured in tree
Conting how many times recurion occured in tree

Time:12-04

Hi I need help with this function:

    def order_of_succession(self, alive: Set[int], succesors: Optional[List[List[int]]] = None, order: int = 1) -> Dict[int, int]:
        if succesors is None:
            succesors = []
        for child in self.children:
            temp = []
            if child.pid in alive:
                temp.append(child.birth_year)
                temp.append(order)
                temp.append(child.pid)
                succesors.append(temp)
            child.order_of_succession(alive, succesors, order   1)
        succesors = sorted(succesors, key=lambda x: (x[0], x[1]))
        succesion = {}
        for elem in succesors:
            succesion[elem[2]] = elem[1]
        return succesion

Only problem I have is that every time recursion is completed on one child order changes back to starting order on first child that was checked. This is output from that function:

{127: 1, 290: 1, 561: 2, 490: 2, 611: 2, 702: 2, 390: 3, 590: 3, 106: 4, 429: 4, 1000: 4, 101: 4, 898: 4, 253: 5}

I need order to be increased every time function is called but I dont know how to do it. Thaks for any help.

CodePudding user response:

There's no good way to do what you want with your current recursive API, since you can't readily return an updated order (since you're already returning something else). However, if you change things up so the recursive function is a helper to the main function, you can use a nonlocal variable to handle it properly:

def order_of_succession(self, alive: Set[int]) -> Dict[int, int]:
    successors: List[List[int]] = []   # both of these variables will be updated in helper
    order = 1

    def helper(person):
        nonlocal order                         # this lets us modify order
        for child in person.children:
            if child.pid in alive:
                successors.append([child.birth_year, order, child.pid])
                order  = 1                     # which we do here
            helper(child)

    helper(self)

    succesors = sorted(succesors, key=lambda x: (x[0], x[1]))    # the rest is unchanged
    succesion = {}
    for elem in succesors:
        succesion[elem[2]] = elem[1]
    return succesion

This isn't quite what you asked for, as I only update the order for living children. If you want the order to increment even when you recurse on a non-living child, you can move the order = 1 line outside the if statement.

  • Related