Getting min/max in a sequence greater/less than some value

Sometimes it is useful to know what is the smallest value in a sequence greater than (or equal to) some other value. Eg.

max_lt([2, 3, 5, 7, 11], 6) would be 5, because 5 is greatest value in the list which is also less than 6. Following the same lines method call min_gt([3, 5, 6, 10, 12], 6) would return 10, because 10 is the smallest value in the list greater than 6. The following four simple methods implement min_gt, min_le, max_gt and max_ge, but the input must be sorted for them to work.

However, Greg Jorgensen's suggestion is much more clever. No need for sorting, just use list comprehensions with min/max.


An example follows:

<pre> percentages = range(0, 100, 5) # all percentages from 0 to 95 at 5-step intervals

give as large share for each object as possible, using those fixed percentages

items_to_share = 148

for obj in mycontainer: my_share = max_le(percentages, items_to_share/len(mycontainer)) # convert it to percentage my_share /= 100.0

obj.acquire_items(int(my_share*items_to_share)) </pre>

Now each object get as much items as possible so that total percentage is An example follows:

<pre> percentages = range(0, 100, 5) # all percentages from 0 to 95 at 5-step intervals

give as large share for each object as possible, using those fixed percentages

items_to_share = 148

for obj in mycontainer: my_share = max_le(percentages, items_to_share/len(mycontainer)) # convert it to percentage my_share /= 100.0

obj.acquire_items(int(my_share*items_to_share)) </pre>

Now each object get as much items as possible so that total percentage is

def min_gt(seq, val):
    """
    Return smallest item in seq for which item > val applies.
    None is returned if seq was empty or all items in seq were <= val.

    >>> min_gt([1, 3, 6, 7], 4)
    6
    >>> min_gt([2, 4, 7, 11], 5)
    7
    """

    for v in seq:
        if v > val:
            return v
    return None

def min_ge(seq, val):
    """
    Same as min_gt() except items equal to val are accepted as well.

    >>> min_ge([1, 3, 6, 7], 6)
    6
    >>> min_ge([2, 3, 4, 8], 8)
    8
    """

    for v in seq:
        if v >= val:
            return v
    return None

def max_lt(seq, val):
    """
    Return greatest item in seq for which item < val applies.
    None is returned if seq was empty or all items in seq were >= val.

    >>> max_lt([3, 6, 7, 11], 10)
    7
    >>> max_lt((5, 9, 12, 13), 12)
    9
    """

    idx = len(seq)-1
    while idx >= 0:
        if seq[idx] < val:
            return seq[idx]
        idx -= 1
    return None

def max_le(seq, val):
    """
    Same as max_lt(), but items in seq equal to val apply as well.

    >>> max_le([2, 3, 7, 11], 10)
    7
    >>> max_le((1, 3, 6, 11), 6)
    6
    """

    idx = len(seq)-1
    while idx >= 0:
        if seq[idx] <= val:
            return seq[idx]
        idx -= 1

    return None

code.activestate.com ↗