Reputation: 13
Hi I am trying to understand how recursion works. I am aware recursion calls itself repeatedly. I am curious to know if recursion can be used to solve simple problems like creating a list from 0 to 9. Here is the program I am trying to convert to recursion:
For loop version
def create_list(start, count):
mylist = []
for i in range(start, start + count):
mylist.append(i)
return mylist
the_list = create_list(0, 8)
print(the_list)
Broken recursive version
def create_list(start, count):
mylist = []
mylist = create_list_recurse(start, start + count)
return mylist
def create_list_recurse(start, end):
if start >= end:
return
create_list_recurse(start + 1, end)
print(create_list(0, 9))
I got stuck making the recursive version work. The program will just return a list of values. Please tell me if I took the wrong approach to solve this.
Upvotes: 1
Views: 3542
Reputation: 512
Mark and RufusVS have explained very well, but if you want to understand it with your code since you asked what you did wrong. Here is it:
def create_list(start, count):
mylist = []
mylist = create_list_recurse(start, start + count)
return mylist
def create_list_recurse(start, end):
#print(start, end)
if start < end:
return [start] + create_list_recurse(start + 1, end)
elif start==end:
return [start]
print(create_list(0, 9))
Upvotes: 1
Reputation: 4127
Your problem is your recursive function has to return a value up to the previous level. The recursive function also has to have a termination condition so it doesn't keep calling itself. Your list function is an interesting example, what you want to do is generate an element of the list, and a shorter list:
def create_list(start, length):
if length:
return [start]+create_list(start+1, length-1)
else:
return []
print (create_list(0,8))
Upvotes: 1
Reputation: 92440
You don't need the second function or any outside variables. You simply need an edge condition to know when to stop and then recursion that does something. Here that something can be creating a part of your list and recursing to get the rest.
It's often helpful think about the edge case first, then think about what happens with one recursive call.
You also need to remember to return from your function (and think about what the edge condition should return (for example an empty list):
def create_list_recurse(start, end):
if start > end:
return []
return [start] + create_list_recurse(start + 1, end)
create_list_recurse(0, 9)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
create_list_recurse(3, 1) #edge case returns empty
# []
Upvotes: 1