简体   繁体   中英

How to limit the number of recursive calls to 2 functions simultaneously? - Python

def f1(t):
    if t < 0:
        return 0
    result = 0
    result = 1.5 * f2(t-1) + 3.5 * f1(t-1)
    return result

def f2(t):
    if t < 0:
        return 1
    result = 0
    result = 1.5 * f1(t-1) + 3.5 * f2(t-1)
    return result

for i in range(10):
    result = 0
    result = f1(i) + f2(i)
    print(result)

Running the above code takes a lot of time. I want to limit the number of executions of f1() and f2() to 10 executions each for every iteration in the for-loop , then proceed to the next for-loop value. How to do so?

Edit: 1. original pseudo code for this part 2. actual functions

I sometimes need a similar method to debug recursive code. A very simple method is to declare a variable in a scope outside the recursive function.

iterations_f1 = 10
iterations_f2 = 10

Then add some logic temporarily inside the recursive function to return before another recursive call if the iterations have been met.

def f1(t):
  global iterations_f1
  iterations_f1 = iterations_f1 - 1
  if iterations_f1 == 0:
    return

  # rest of funtion
  ...

You could use a keyword argument to pass on the recursion depth.

def f1(t, _max_depth=10):

    if _max_depth > 0:
        if t < 0:
            return 0
        result = 0
        result = 1.5 * f2(t-1, _max_depth=_max_depth - 1) + 3.5 * f1(t-1, _max_depth=_max_depth - 1)
        return result

    else:
        # return some default value here

You can do the same for f2 .

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