What is tail recursion?

Keywords: Python

50% of algorithm problems can be solved by recursion, which is not to say how powerful recursion itself is, but to say that recursion makes many complex problems simple! Why? People who understand data structure know that tree structure itself is defined by recursion

What is tail recursion?

As we all know, recursion will record the call state of the last function, resulting in a large number of resource occupation. In order to minimize the resource occupation, the recursion method is to put the recursion operation in return. Since return is the last sentence of the function, the space of recording the function body can be reduced


Two recursive methods

Common recursive writing

function recursion(num){
    new_num = num + 1
    if (num >= 20000){
        return
    }
    console.log("General recursion|The first",new_num,"Secondary call")
    recursion(new_num)
}

recursion(1)

Tail recursion (return the function call directly)

// Tail recursion
function recursion2(num){
    new_num = num + 1
    if (num >= 20000){
        return
    }
    console.log("Tail recursion|The first",new_num,"Secondary call")
    return recursion2(new_num)
}
recursion2(1)

Tail recursion saves the memory consumption of the middle stack in the recursion process, but this kind of playing method can't break the recursion stack limit (python is about 1000 times, Chrome js environment is about 20000 times). The function recursionreturn itself doesn't parse and free space,
In order to verify the above statement, take Python as an example (js is hard to write, or Python is easy to use...)

Structural timing

class Recursion(object):
    def __init__(self, num):
        self.num = num
        print("object obj",self.num, "establish")

    def __del__(self):
        print("object obj", self.num-1, "Deconstruction")
    # Tail recursion
    def add(self):
        print(">>Tail recursion|The first",self.num,"second")
        self.num += 1
        if (self.num>10):
            return
        else:
            return Recursion(self.num).add()
    # Normal recursion
    def add2(self):
        print(">>Normal recursion|The first",self.num,"Secondary recursion")
        self.num += 1
        if (self.num>10):
            return
        else:
            Recursion(self.num).add2()  

def main():
    # Tail recursion
    recu = Recursion(1)
    recu.add()
    # Normal recursion
    recu2 = Recursion(1)
    recu2.add2()

if __name__ == '__main__':
    main()

Posted by redsox8185 on Tue, 31 Mar 2020 17:15:08 -0700