-1

I'm quite new to recursion and I have to solve a problem for my homeworks which asks to define a recursive function to get the next element on a given item of a list. I made the iterative version but I don't understand how to write the recursive one.

def next_value(lst,v):
   ind = lst.index(v)
   list1_result = lst[ind+1]
   return list1_result

a = [4, 2, 10, 3, 2, 5]
print(next_value(a,10))

# output: 3
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Mizze
  • 3
  • 1

1 Answers1

2

Your solution seems okay but if it absolutely has to be recursive, here's an example implementation:

def next_value(lst, v):
  if (len(lst) < 2):
    return None
  if (lst[0] == v):
    return lst[1]
  return next_value(lst[1:], v)

Basically we pass slices from the same list until we find an element with the given value. If the length is less than 2, the list is either empty or we have looked through it all. In that case we return None to denote that there is no valid answer.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93