Home > Enterprise >  If number is not in list return next highest number python
If number is not in list return next highest number python

Time:10-28

I need method of checking whether a number exists is a list/series, and if it does not returning the next highest number in the list.

For example:- in the list nums = [1,2,3,5,7,8,20] if I were to enter the number 4 the function would return 5 and anything > 8 < 20 would return 20 and so on.

Below is a very basic example of the premise:

nums = [1,2,3,5,7,8,20]

def coerce_num(x):
    if x in nums:
        return print("yes")
    else:
        return ("next number in list")

coerce_num(9)

If there was a method to do this with pandas dataframe, that would be even better.

CodePudding user response:

You can achieve this using the recursive function coerce_num(x 1) it will add 1 and try to search again.

Method 1

nums = [1,2,3,5,7,8,20]

def coerce_num(x):
    if x > max(nums):
        return None 
    if x in nums:
        return print("yes", x)
    else:
        coerce_num(x   1)

coerce_num(6)

Method 2

nums = [1,2,3,9,7,8,20]
nums.sort()
def coerce_num(x):
    for i in nums:
        if x == i:
           return print("yes", x)
        if x < i:
           return print("next highest", i)

CodePudding user response:

Here's one way using standard Python (nums doesn't need to be sorted):

def coerce_num(x):
    return min((n for n in nums if n >= x), default=None)
>>> coerce_num(4)
5
>>> coerce_num(9)
20

(added default=None in case no numbers are greater than x)

  • Related