i have homework in which i must use recursion to find all occurances of a number/letter/word in a list and return their index in the original list.. I have searched this site for previously answered question but I couldn’t find any answer regarding recursion with the option to continue checking the list even after the first occurances has been found..
should look like this pretty much:
>>> find_value( [4,7,5,3,2,5,3,7,8,6,5,6], 5)
[2,5,10]
my code so far goes like this:
def find_all(x,y):
if len(x) == 1 and x[0] == y:
return [i for i, y in enumerate(x)]
return find_all(x[1:],y)
Though it only minimize the list and gives me the same [0] as the index.. which is true, for the divided list.. this way I will never get the original index..
Thanks
– if this already exist, I am sorry for i have searched and couldn’t find.
The point of assigning a homework is usually so that you can explore the problem and learn from it. In this case, it is recursion which is usually hard for beginners.
The point of recursion is to construct an answer for a larger problem from a solution of a smaller ones. So it is best to start off with the smallest one possible:
If the list is not empty, we can check if the first element is what we are looking for:
We will also need the solution to the smaller problem:
Now the problem you have noticed is that the indices that are returned are always 0. That’s because they are indices in the smaller list. If an item has index
0in a smaller list, it means its index in the largest list is actually1(this is the main part your program was missing), thus:And return the complete answer:
I hope this helps you a bit, so you can do your next homework on your own.