Python Recursion not exiting the function, Find the last index of 'x' in the 'arr' recursively

49 Views Asked by At

Read input as specified in the question

Print output as specified in the question.

arr=[34, 57, 82, 41, 65, 35, 82, 27, 36, 12, 6, 40, 66, 99, 25, 29, 22, 25, 12, 24, 65, 15, 5, 43, 28, 33, 76, 32, 13, 95, 22, 84, 71, 23, 28, 7, 65, 94, 18, 47, 9, 42, 61, 73]
x=61
si = 0
def lastIndex(arr, x, si):
    arrLen = len(arr)
    lastKnownIndex = -1
    if (arrLen == 0):
        return lastKnownIndex
    if (si == arrLen):
        if (arr[si] == x):
            lastKnownIndex = si
        return lastKnownIndex
    if (arr[si] == x):
        lastKnownIndex = si
    lastIndex(arr, x, si + 1)
    return lastKnownIndex

print(lastIndex(arr, x, si))
1

There are 1 best solutions below

0
qouify On

You do not have an infinite recursion but an IndexError exception. The problem comes from these two lines:

    if (si == arrLen):
        if (arr[si] == x):

The second line will always raise an exception since if si == arrLen then arr[si] is equivalent to arr[len(arr)] which is always wrong (remember that list items are indexed from 0 to len(arr) - 1).

Here is a patched version that fixes this bug and simplifies a bit your code:

arr=[34, 57, 82, 41, 65, 35, 82, 27, 36, 12, 6, 40, 66, 99, 25, 29, 22, 25, 12, 24, 65, 15, 5, 43, 28, 33, 76, 32, 13, 95, 22, 84, 71, 23, 28, 7, 65, 94, 18, 47, 9, 42, 61, 73]
def lastIndex(arr, x, si=0):
    #  empty list or end of list reached
    if si >= len(arr):
        return -1
    #  x is at position si
    if arr[si] == x:
        return si
    #  owtherwise look at next position
    return lastIndex(arr, x, si + 1)

print(lastIndex(arr, 61))  #  print 42