简体   繁体   中英

Recursion Error. Having trouble understanding the logic with recursive functions

from functools import lru_cache

@lru_cache(maxsize=1000)
def recursiveFunc(x):
    if x == 1:
        return 1
    elif x > 1 :
        return recursiveFunc(x) + recursiveFunc(x+1) #This is the part i'm having doubts about. 

for x in range(1, 101):
     print(x, ":", recursiveFunc(x))

This functions is supposed to generate consecutive numbers starting from 1 to 100 using recursion.

Your problem is that you have to learn very well all the recursion story, it takes time... you have to visualize what the program is executing in every step. My advice is to draw the first times the stack buffer with every call of the function


The solution of your problem is:

def recursiveFunc(x):
    if x == 1:
        return 1
    elif x > 1 :
        return 1 + recursiveFunc(x-1) #This is the part I've changed.

for x in range(1, 101):
    print(x, ":", recursiveFunc(x))

Why your doesn't work? Cause when the function calls return, return start the new function recursiveFunc(x)... but it's just the same of before! so there is an infinite loop. Furthermore if you add like recursiveFunc(x+1) and you pass x that are positive you will never made the comparison x == 0 cause x it's growing call after call.

Here I'll try to clear things up for you :)

Writing a function that lists numbers from 1 to n is simple. If we tried running this function

def recursiveFunc(i):
   print(i)
   recursiveFunc(i+1)

recursiveFunc(1)

It would print out 1, then 2, 3.... But would never stop.

1
2
3
...

To fix this we add a second parameter

def recursiveFunc(i, n):
   if i > n:
      return

   print(i)
   recursiveFunc(i+1)

recursiveFunc(1, 100)

This will escape the function when it passes n, in this case, 100

1
2
...
100

if you wanted to return the series rather than just print it out you could do something like this:

def recursiveFunc(i, n):
   if i >= n:
      return str(i)

   return str(i) + ", " + str(recursiveFunc(i + 1, n))

print(recursiveFunc(1, 100))

Then the output would be

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100

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