Home > Software engineering >  How to return a value through recursive call in Python
How to return a value through recursive call in Python

Time:11-22

I am trying a to solve a problem. There are a few programs where I have to return a value in variable throughout various function calls(Recursive calls). I am not sure how to do that.

I am trying Merge Sort algorithm in python this is the implementation:

def merge(arr,lo,hi):
    mid=(lo hi)//2
    c=0
    i=lo; j=mid 1; k=0;
    temp=[]
    
    while(i<=mid and j<=hi):
        if arr[i]>arr[j]:
            temp.append(arr[j])
            c =mid-i 1
            j =1
            k =1
        else:
            temp.append(arr[i])
            i =1
            k =1
            
    while(i<=mid):
        temp.append(arr[i])
        i =1
        k =1
    while(j<=hi):
        temp.append(arr[j])
        j =1
        k =1
    for i in range(k):
        arr[lo i]=temp[i]
    return c
def mergeSort(arr,lo,hi):
    if lo==hi:
        return
    mid=(lo hi)//2
    mergeSort(arr,lo,mid)
    mergeSort(arr,mid 1,hi)
    merge(arr,lo,hi)

In addition to merge sort I am counting the number of elements which are smaller than a particular element(not much Important). For which I am using a count variable 'c'.
Now I have to return the C value through all the recursive calls and back to my main function. I am not sure how to do that. Someone help me to return it. I also tried returning like this: return mergeSort(arr,lo,mid)

But It just returns 0. My main function gives the call to mergeSort(arr,0,n-1) Thanks in advance.

CodePudding user response:

All you need to do is add up the values returned by each recursive call and by merge, then return that value.

def mergeSort(arr,lo,hi):
    if lo==hi:
        return 0
    c = 0
    mid=(lo hi)//2
    c  = mergeSort(arr,lo,mid)
    c  = mergeSort(arr,mid 1,hi)
    c  = merge(arr,lo,hi)
    return c
  • Related