Home > Blockchain >  I wrote a code for linear search in python(recursive). Can somebody tell me why it isn't workin
I wrote a code for linear search in python(recursive). Can somebody tell me why it isn't workin

Time:01-23

lister=[4,5,1,2,3,6]

i=0
def Search(arr):
    if arr[i]==3:
        return i
    else:
        if i>=0 and i<=(len(arr)-2):          
            i 1
            return Search(arr)
        else:
            return -1

print(Search(lister))

Linear Search using recursion in python.

I don't know why its not working.

CodePudding user response:

There are 2 main issues.
The first is that you're not incrementing i anywhere. i 1 doesn't modify i, just returns the value of i 1 which you're not placing anywhere. To increment i you should use i = 1.
The second is you're not using the externally defined i variable in your Search function.

To fix this you could either declare it as global in the start of your method, or pass it as a parameter to your function.

Global method (less preferable):

lister=[4,5,1,2,3,6]

i=0
def Search(arr):
    global i
    if arr[i]==3:
        return i
    else:
        if i>=0 and i<=(len(arr)-2):          
            i =1
            return Search(arr)
        else:
            return -1

print(Search(lister))

And the parameter method (which would be preferable):

lister=[4,5,1,2,3,6]

def Search(arr, i=0):
    if arr[i]==3:
        return i
    else:
        if i>=0 and i<=(len(arr)-2):          
            i =1
            return Search(arr, i)
        else:
            return -1

print(Search(lister))

CodePudding user response:

You are not incrementing i variable. You have i 1 but you don't assign it to i. You should have i=i 1 or i =1 for short. This recursive call function is looping infinitely, since i doesn't change.

CodePudding user response:

Rather than explicitly testing that the index is in range, why not use exception handling? You can also manage the any potential recursion "overflow" in this manner. For example:

def rfind(_list, val, idx=0):
    try:
        if _list[idx] == val:
            return idx
        return rfind(_list, val, idx 1)
    except (IndexError, RecursionError):
        return -1


print(rfind([1, 2, 3], 2))
print(rfind([1, 2, 3], 4)) # will return None due to IndexError
print(rfind([], 4)) # will return None due to IndexError
print(rfind([0]*2000, 1)) # will return None due to RecursionError

Output:

1
-1
-1
-1
  • Related