简体   繁体   中英

how to change this recursion to tail recursion?

here is the recursion code I am trying to change it to tail recursion

def stairClimb(n):
    if n <= 3:
        WaysToClimb = [1, 2, 4]
        return WaysToClimb[n - 1]
    else:
        return stairClimb(n - 1) + stairClimb(n - 2) + stairClimb(n - 3)

When a procedure can recur multiple times per procedure application, to achieve a tail call, we must somehow sequence the multiple recursive calls

Using a technique called continuation-passing style , we can add a second parameter to our function that tells our function what the next step of our computation should be

A simple CPS conversion looks like this

def my_func (x):
  return x

def my_cps_func (x, k)
  # k represents the "next step"
  return k (x)

Python has neat features tho, so we can write our function to support both direct style and continuation-passing style. We do this by assigning a default function as the continuation – we'll use this technique more below, so make sure you understand it here first

               # by default, pass x thru untouched
               # this is known as the "identity" function
def add (x, y, k = lambda x: x):
  return k (x + y)

# direct style
print (add (2, 3)) # 5

# continuation-passing style
add (2, 3, print) # 5

# direct and CPS mixed! invent your own freedom
print (add (2, 3, lambda sum: add (sum, sum))) # 10

Your stair_climb is like a 3-fibonacci procedure (sometimes called " tribonacci ") only yours uses a unique (1,2,4) seed instead of a more traditional (0,0,1) seed – we'll show tribonacci converted to CPS then we'll look at your procedure after that

def tribonacci (n, k = lambda x: x):
  if n == 0:
    return k (0)
  elif n == 1:
    return k (0)
  elif n == 2:
    return k (1)
  else:
    return tribonacci (n - 1, lambda a:
      tribonacci (n - 2, lambda b:
        tribonacci (n - 3, lambda c:
          k (a + b + c))))

for x in range (1,10):
  print (tribonacci (x))

# 0
# 1
# 1
# 2
# 4
# 7
# 13
# 24
# 44

But the time complexity of that function is O (3 n ) - since lambdas can abstract any number of values, this can be massively optimized by using a multi-parameter lambda – here we compute the same answer in O (n) where lambda a, b, c: ... represents our "seed"

                   # by default, return the first value of the seed
def tribonacci (n, k = lambda a, b, c: a):
  if n == 0:
           # base seed values
    return k (0, 0, 1)
  else:
                              # the next seed (this is our "next step")
    return tribonacci (n - 1, lambda a, b, c:
      # new seed
      #  b is the "next a"
      #     c is the "next b"
      #        the sum of each is the "next c"
      k (b, c, a + b + c))

for x in range (1,10):
  print (tribonacci (x))

# 0
# 1
# 1
# 2
# 4
# 7
# 13
# 24
# 44

All we have to do is change the k (0, 0, 1) seed to k (1, 2, 4)

def stair_climb (n, k = lambda a, b, c: a):
  if n == 0:
    return k (1, 2, 4)
  else:
    return stair_climb (n - 1, lambda a, b, c:
      k (b, c, a + b + c))

for x in range (1,10):
  print (stair_climb (x))

# 2
# 4
# 7
# 13
# 24
# 44
# 81
# 149
# 274

And yep, if you look at each line, every procedure application is in tail position

def stair_climb (n, k = lambda a, b, c: a):
  if n == 0:
           # tail
    return k (1, 2, 4)
  else:
           # tail
    return stair_climb (n - 1, lambda a, b, c:
      # tail
      k (b, c, a + b + c))

But you have a bigger problem – Python doesn't have tail call elimination

print (stair_climb (1000))
# RecursionError: maximum recursion depth exceeded in comparison

No worries, once you're using continuation-passing style, there's all sorts of ways around that

use accumulator:

def stairClimb(n, acc, acc1, acc2):

if n == 3:
    return acc2
else:
    return stairClimb(n-1, acc1, acc2, acc+acc1+acc2)

and call it with the initial numbers:

stairClimb(n, 1, 2, 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM