Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does return -1 here mean?

Tags:

python

return

When looping up answers to some job interview questions, I got this bit of code and am confused as to what return -1 is doing, and I guess how this code is actually accomplishing the task.

#First Non-Repeating Integer in an Array
def firstNonRepeating(arr, n): 
  
    for i in range(n): 
        j = 0
        while(j < n): 
            if (i != j and arr[i] == arr[j]): 
                break
            j += 1
        if (j == n): 
            return arr[i] 
      
    return -1
      
# Driver code 
arr = [ 9, 4, 9, 6, 7, 4 ] 
n = len(arr) 
print(firstNonRepeating(arr, n)) 
like image 794
0004 Avatar asked Jun 30 '26 11:06

0004


2 Answers

It looks like it's being used as a sentinel value for when all the integers repeat, for example:

>>> a = [9, 4, 9, 4]
>>> firstNonRepeating(a, len(a))
-1

However, that's a terrible choice of sentinel value, because it's also a perfectly legal value:

>>> arr = [-1]
>>> print(firstNonRepeating(arr, len(arr)))
-1

It would be better to raise an exception, like:

raise ValueError('no non-repeating integer found')

Maybe the writer was thinking of unsigned integers, which don't exist in Python (at least not as a native type). There are a bunch of other oddities that make me think it was written by someone more familiar with say, C, than Python (namely, passing in the length of an array, looping over numbers with while instead of for ... range, referring to a list/sequence as an array, and parentheses around the if tests).

like image 174
wjandrea Avatar answered Jul 03 '26 00:07

wjandrea


Generally when there is no solution present for the given input, then for indication purpose -1 is returned as the answer.

Here function firstNonRepeating will return -1 when all the integers present at least twice in the array.

like image 27
vkswhy Avatar answered Jul 02 '26 23:07

vkswhy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!