Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to find the floor and ceiling of the value N in an unsorted list with Python

1 Answer

0 votes
import sys

def find_floor_and_ceil(lst, N):
    floorval = -sys.maxsize - 1  # Equivalent to INT_MIN
    ceilval = sys.maxsize        # Equivalent to INT_MAX

    for num in lst:
        if num <= N and num > floorval:
            floorval = num  # Update floorval if num is closer to N
        if num >= N and num < ceilval:
            ceilval = num  # Update ceilval if num is closer to N

    # If no valid floorval or ceilval is found, set them to a special value
    if floorval == -sys.maxsize - 1:
        floorval = -1  # No floorval exists
    if ceilval == sys.maxsize:
        ceilval = -1  # No ceilval exists

    return floorval, ceilval

lst = [4, 10, 8, 2, 6, 9, 1]
N = 5  # Value to find floor and ceil for

floorval, ceilval = find_floor_and_ceil(lst, N)

print("floor:", "None" if floorval == -1 else floorval)
print("ceil:", "None" if ceilval == -1 else ceilval)



'''
run:

floor: 4
ceil: 6

'''

 



answered Nov 8, 2025 by avibootz
...