Home > Blockchain >  Tail recursive function for the equation Tn=n∑k=1 =k
Tail recursive function for the equation Tn=n∑k=1 =k

Time:12-01

I need to write the tail recursive function for the equation Tn=n∑k=1 =k (sum from k=1 to n) in python. I was able to write the non tail recursive

def TN(n):
    if n == 0:
        return 0
    return n   TN(n-1)

I tried:

def TN(n):
    if n==0:
        return 0;
    s=n TN(n-1)
    return s

Does this count as the tail recursive function of the first code? If not how can write it?

CodePudding user response:

For the function to be tail recursive, calling itself needs to be the last and only thing it does on the return statement. For your specific case, this could be achieved by passing down a defaulted parameter that you return on you base condition:

def Tn(n,result=0):
    if not n: return result
    return Tn(n-1,result n)

Note that Python does not actually support tail recursion. This will be processed as a regular recursion and will be subject to maximum recursion depth limitations even though it is in tail-recursion form

  • Related