-1

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.

John Conor
  • 722
  • 6
  • 20
  • 2
    A couple of questions... 1) Is your `nums` list sorted? 2) What do you want it to happen if the user enters `21`? – Savir Oct 27 '22 at 20:03
  • 2
    Assuming the list is sorted, Python's `bisect.bisect_right` will return to you the index just after your goal. `nums[idx-1]` might equal your value. – Tim Roberts Oct 27 '22 at 20:05

4 Answers4

2

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)

sj95126
  • 6,520
  • 2
  • 15
  • 34
0

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)
0

Assuming a sorted list, use bisect for an efficient binary search:

import bisect

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

def coerce_num(nums, x):
    return x[bisect.bisect_left(x, nums)]

coerce_num(8, nums)
# 8

coerce_num(20, nums)
# 20

coerce_num(0, nums)
# 1
mozway
  • 194,879
  • 13
  • 39
  • 75
0

Assuming input list is pre-sorted prior to passing into the function below.

import numpy as np


def check_num(list_of_nums, check):
    # use list comprehension to find values <= check
    mask=[num <= check for num in list_of_nums]
    # find max index
    maxind = np.max(np.argwhere(mask))
    # if index is last num in list then return last num (prevents error)
    # otherwise, give the next num
    if maxind==len(list_of_nums)-1:
        return list_of_nums[-1]
    else:
        return list_of_nums[maxind+1]


nums = [1,2,3,5,7,8,20]
print(check_num(nums, 6))

hknjj
  • 319
  • 1
  • 8