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))
You do not have an infinite recursion but an
IndexErrorexception. The problem comes from these two lines:The second line will always raise an exception since if
si == arrLenthenarr[si]is equivalent toarr[len(arr)]which is always wrong (remember that list items are indexed from0tolen(arr) - 1).Here is a patched version that fixes this bug and simplifies a bit your code: