Reputation: 11
In Python, how can we provide a function that takes as input:
and then provides as an output the rank of the number in the array? If the number is not part of the array then it should be the rank of the number lower than the value given.
For example, if the function was given
[1.2,4.3,5,7.23,63.1]
, then the rank should be 4.[1.2,4.3,5,7.23,63.1]
, then the rank should be 1.[1.2,4.3,5,7.23,63.1]
, then the rank should be 5.Upvotes: 0
Views: 68
Reputation: 13
I think its best to try and solve this question yourself first to get some practice, but if you have tried and you are now looking for a solution below is a simple way of doing so.
Note the below solution assumes the array is sorted. The elif
also isn't necessary due to the return above (can replace it with if
), but for readability I have included it
def getRank(arr, value):
for index, arrVal in enumerate(arr):
if arrVal == value:
return index + 1
elif arrVal > value:
return index
return len(arr)
Another note, this is a simple O(n) solution as you have to at worst iterate through the whole array. Assuming the list is sorted a binary tree solution could be done with a complexity of O(logn)
Upvotes: 0
Reputation: 262604
Assuming the list/array is sorted, you can use bisect.bisect_right
:
from bisect import bisect_right
bisect_right(array, number)
Example:
bisect_right([1.2,4.3,5,7.23,63.1], 7.23)
4
bisect_right([1.2,4.3,5,7.23,63.1], 3.5)
1
bisect_right([1.2,4.3,5,7.23,63.1], 100)
5
Upvotes: 1