0

I’m returning count here, which before the return statement gives <type 'int'> but after it gets returned the output I get is None.

def equal(arr,count):
 arr = sorted(arr)
 if arr[0]==arr[-1]:
    
    print(count) # the answer I’m getting is correct so I don’t 
                  #think there’s a problem with rest of the code
    return count

 if (arr[-1]-arr[0])>=5:
     diff=5
 elif(arr[-1]-arr[0])>=2:
     diff=2
 else:
     diff=1
 for i in range(len(arr)-1):
     arr[i]+=diff

 count+=1
 equal(arr,count)


 a=[10,7,12]
 print(equal(a,0)) # I'm getting output here as **None**enter code here
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

2

Your function returns only if the if condition, is true as in lines :

 if arr[0]==arr[-1]:
    
    print(count) # the answer I’m getting is correct so I don’t 
                  #think there’s a problem with rest of the code
    return count

But if the condition, arr[0]==arr[-1] is false, your function does not return anything, that is why it is returning a None type. Add a return when the function calls itself in the body, with the line equal(arr,count) changed to return equal(arr,count)

def equal(arr,count):
    arr = sorted(arr)
    if arr[0]==arr[-1]:
    
        print(count) # the answer I’m getting is correct so I don’t 
                  #think there’s a problem with rest of the code
        return count

    if (arr[-1]-arr[0])>=5:
        diff=5
    elif(arr[-1]-arr[0])>=2:
        diff=2
    else:
        diff=1
    for i in range(len(arr)-1):
        arr[i]+=diff

    count+=1
    return equal(arr,count)


a=[10,7,12]
print(equal(a,0)) # I'm getting output here as **None**enter code here
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
1

Your if clause fails, and then you are not returning anything. In that case, python implicitly returns None. Add an else clause to return something in case the if fails

blue_note
  • 27,712
  • 9
  • 72
  • 90