def index(L,v)
''' Return index of value v in L '''
pass
I need help with implementing this function using recursion. Really new to recursion stuff so any advice would help!
Note that L is a list. v is a value.
That works
def recursive_index(L, v):
return 0 if L[0] == v else 1 + recursive_index(L[1:], v)
but is pretty stupid (and will only work if the value exists)
You can add if v not in L: return -1 to make it work for any case, but that is even worst.
Do it really has to be recursive?
I assume this is homework.
So you need to understand recursion. Here's an example:
def countdown(n):
if n == 0:
print "Hello World!"
else:
print n
countdown(n-1)
You need to start with a starting point, in your case it would probably be the 0th element.
You need an end point, which should be the length - 1 or when you find the element.
Simple if else should do here, with a modified version of countdown as above.
Yet another way:
def rec(l,v, index=0):
try:
if l[index] == v:
return index
except IndexError:
return -1
return rec(l,v,index+1)
Here a tail recursive version of it:
def indexof(elem, list_):
return indexof_tailrec(elem, list_, 0)
def indexof_tailrec(elem, list_, index):
if index >= len(list_):
return None
if list_[index] == elem:
return index
return indexof_tailrec(elem, list_, index + 1)
Note, however, that Python does not have tail call optimization (at least not as far as I know).
A recursive solution to find the first occurence of an element using Binary Search is this -
def Binary_Search(l, val, low, high):
if low > high:
return -1
mid = (low+high)//2
if len(l) == 1:
if l[0] == val:
return 0
return -1
if l[mid] == val:
if mid == 0 or l[mid-1] != l[mid]:
return mid
else:
return Binary_Search(l, val, low, mid-1)
elif l[mid] < val:
return Binary_Search(l, val, mid+1, high)
else:
return Binary_Search(l, val, low, mid-1)
def fi(arr,x):
if len(arr)==0:
return -1
elif arr[0]==x:
return 0
k= fi(arr[1:],x)
if k== -1:
return -1
else:
return k+1