I am new about Python. I wrote a function about returns the number of occurences of x in the sorted repeated elements array A:
def FindFirstIndex(A, low, high, x, n):
low = 0
high = len(A) - 1
if low <= high:
mid = low + (high - low) / 2
if (mid == 0 or x > A[mid - 1]) and A[mid] == x:
return mid
elif x > A[mid]:
return FindFirstIndex(A, (mid + 1), high, x, n)
else:
return FindFirstIndex(A, low, (mid - 1), x, n)
return -1
def FindLastIndex(A, low, high, x, n):
low = 0
high = len(A) - 1
if low <= high:
mid = low + (high - low) / 2
if (mid == n - 1 or x < A[mid + 1]) and A[mid] == x:
return mid
elif x < A[mid]:
return FindFirstIndex(A, low, (mid - 1), x, n)
else:
return FindFirstIndex(A, (mid + 1), high, x, n)
return -1
def COUNT(A, x):
i = FindFirstIndex(A, 0, len(A) - 1, x, len(A))
if i == -1:
return i
j = FindLastIndex(A, i, len(A) - 1, x, len(A))
length = j - i + 1
return length
The error is: RuntimeError: maximum recursion depth exceeded. Anybody knows how to solve it?
FindFirstIndexplease provide aelifcondition what you have to check.Otherwise it is repeating every time if above twoifconditions are false - itzMEonTVFindFirstIndex.low=0high=len(A) - 1.if low<=highfrom else conditionelse: return FindFirstIndex(A, low, (mid - 1), x, n), Here now check,low,highis always fixed if your else condiion satisfies.So it is recursively repeating.Thats the error. You are changingmidtomid-1in recursive function.But it is not checking anywhere.Also you definedmidas a value fromlowandhighwhich never changing if above condition satisfies - itzMEonTV