0

I have a recursive function, I have no idea why the result printed in main is always None.

def find_nega(A: list, start: int, right: int) -> int :

    s = start
    r = right
    mid = (s + r) // 2

    if (s >= r):
        return None

    if (A[mid] == 0):
        return mid - 1

    if (A[s] < 0 and A[r] >= 0 and s == r - 1):
        print(s)
        return s

    if (A[mid] < 0):
        s = mid
        find_nega(list1, s, r)

    elif (A[mid] > 0):
        r=mid
        find_nega(list1, s,r)
    else:
        return mid

if __name__ == "__main__":

    list1 = [-3,-2,-1,4,5,6]
    x = find_nega(list1, 0, len(list1) - 1)
    print(x)

In this example, it enters the condition A[s] < 0 and A[r] >= 0 and s == r - 1 but don't know why it doesn't print 2.

SadSalad
  • 69
  • 2
  • 12

1 Answers1

0

It doesn't print 2 because you don't return the value when you call the recursion. Here it works

def find_nega(A: list, start: int, right: int) -> int:
    print(A, start, right)
    s = start
    r = right
    mid = (s + r) // 2

    if s >= r:
        return None

    if A[mid] == 0:
        return mid - 1

    if A[s] < 0 and A[r] >= 0 and s == r - 1:
        #print(s)
        return s

    if A[mid] < 0:
        s = mid
        return find_nega(list1, s, r)

    elif A[mid] > 0:
        r = mid
        return find_nega(list1, s, r)
    else:
        return mid


if __name__ == "__main__":

    list1 = [-3, -2, -1, 4, 5, 6]
    x = find_nega(list1, 0, len(list1) - 1)
    print(x)
Andrea Pollini
  • 292
  • 4
  • 8