Home > Mobile >  How can i modify the program to return false if the value is not present in an Array
How can i modify the program to return false if the value is not present in an Array

Time:11-07

I am using recursion to find an element in an array

def recur_search(arr,n,x): #n is the starting index and x is the target value
    if (arr[n] == x):
        return n
    else:
        return recur_search(arr,n 1,x)

arr = [1,2,3,4,5,6,7,8]

print(recur_search(arr,0,5))

This program only works if i have the element present in the array. If the element is not present the program is throwing IndexErrors. Is there a graceful way to tackle the problem

type here

I was thinking of checking the presence of element using iteration first but that beats the purpose of recursion. Is there a way to use recursion to find the element if it's present and if its not

CodePudding user response:

I think you could make the first condition to check if the index is out of bound, then the element doesn't exist, like so:

def recur_search(arr,n,x): #n is the starting index and x is the target value
    if n == len(arr):
        return False
    elif (arr[n] == x):
        return n
    else:
        return recur_search(arr,n 1,x)

arr = [1,2,3,4,5,6,7,8]

print(recur_search(arr,0,5))

CodePudding user response:

If you really insist on using recursion for this then:

def recur_search(arr, x):
    def _search(arr, n, x):
        if n < len(arr):
            if arr[n] == x:
                return n
            return _search(arr, n 1, x)
    return _search(arr, 0, x)


arr = [1, 2, 3, 4, 5, 6, 7, 8]

print(recur_search(arr, 5))

Output:

4
  • Related