Home > OS >  How to check if all elements in an array are equal using recursion in Python?
How to check if all elements in an array are equal using recursion in Python?

Time:05-14

I am practising recursion and am not sure why my code is failing.

def isEqual(arr, n):
    if(n==1):
        return arr[n]
    return arr[n-1]==isEqual(arr, n-1)

The logic is quite generic. I assume that I have a method that can check whether all elements in my array until length n-1 are equal, isEqual(arr, n-1). Next, I check if the nth element is equal to the preceding elements using arr[n-1]==isEqual(arr, n-1).

However, the code fails for basic test cases such as -

arr = [5,5,5,5,5,5]
isEqual(arr, len(arr))

Could someone point me towards where I am going wrong?

CodePudding user response:

You are mixing up returning a value v.s equality check. There are many ways to correct it, but here is an example

def isEqual(arr, n):
    if(n<=0):
        return True
    return arr[n-1]==arr[n] and isEqual(arr,n-1)
arr = [5,5,5,5,5,5]
print(isEqual(arr, len(arr)-1))
brr = [1,2,3,4,5]
print(isEqual(brr, len(brr)-1))
crr=[False]*5
print(isEqual(crr, len(crr)-1))
  • Related