Suppose a list [4,8,15,16,23,42]
Given the input value n
, how do I find the minimum value in the above list that is greater than n, assuming n is not in the list? For example, 5 would yield 8, 17 would yield 23, 39 would yield 42, etc.
CodePudding user response:
You can sort the list, and then traverse the list for the next largest number. Try this:
li = [4, 8, 15, 16, 23, 42]
n = 5
li.sort()
for item in li:
if item > n:
print(item)
break
# output: 8
CodePudding user response:
Say we have:
test_list = [9, 8, 7, 6, 5, 4, 3, 2, 1]
n = 5
First we can keep only numbers greater than n
:
test_list_filtered = [a for a in test_list if a > n]
# resulting list: [9, 8, 7, 6]
Now we can just use min()
to get the smallest item:
print(min(test_list_filtered))
# output: 6
Or, all on one line:
print(min([a for a in test_list if a > n]))
# Output: 6