For example I have a non-ordered list of values [10, 20, 50, 200, 100, 300, 250, 150]
I have this code which returns the next greater value:
def GetN
If I understand you correctly, you want the greatest value that is less than your target; e.g. in your example, if your target is 55, you want 50, but if your target is 35, you want 20. The following function should do that:
def get_closest_less(lst, target):
lst.sort()
ret_val = None
previous = lst[0]
if (previous <= target):
for ndx in xrange(1, len(lst) - 1):
if lst[ndx] > target:
ret_val = previous
break
else:
previous = lst[ndx]
return str(ret_val)
If you need to step through these values, you could use a generator to get the values in succession:
def next_lesser(l, target):
for n in l:
if n < target:
yield str(n)
Both these worked properly from within a simple program.