I have to write a program that finds all of the index values for specific element in list or a string. I have to use recursion, and my function can only take two arguments.
My problem is that my program finds only the first index and then stop. How can I change it to meet my requirements?
My code:
def find_all(L, v):
return 0 if L[0] == v else 1 + find_all(L[1:], v)
Input:
find_all( [1,2,3,4,2,4,5,2,1], 2)find_all("hello wonderful world", "w")
Desired output:
[1,4,7][6,16]
You can use Pythons ability to walk backwards through a list and grab the last element. Then put lists together with the + operator. By going through the list backwards you’re able to find the indice when a value is found, rather than losing it when you move from the start of the list to the end.