How to find the floor of N in a sorted list with Python

1 Answer

0 votes
# floor of N = the largest element in the array smaller than or equal to N

def find_the_floor(lst, N) :
    size = len(lst)
    
    if (N >= lst[size - 1]) :
        return size - 1
    
    if (N < lst[0]) :
        return -1
    
    i = 1
    while (i < size) :
        if (lst[i] > N) :
            return i - 1
        i += 1
    
    return -1
        
lst = [1, 2, 7, 8, 14, 19, 20, 24, 28]
N = 17

index = find_the_floor(lst, N)

if (index == -1) :
    print("The floor doesn\'t exist in array")
else :
    print("The floor of " + str(N) + " is " + str(lst[index]))




'''
run:

The floor of 17 is 14

'''

 



answered Jan 20, 2024 by avibootz

Related questions

1 answer 111 views
1 answer 102 views
1 answer 123 views
1 answer 100 views
1 answer 116 views
1 answer 102 views
...