Python|找到大于 K 的最小元素
给定一个列表,编写一个Python程序来找到大于特定元素 K 的最小数字。
让我们看看解决这个问题的所有方法,从幼稚到单行,以便在需要时可以在编程中使用它们。
方法#1:朴素的方法
使用循环,如果我们发现元素小于前一个值且大于命名变量且大于 K,我们将继续重新初始化命名变量。
# Python3 code to demonstrate
# smallest number greater than K
# using naive method
# Initializing list
test_list = [1, 4, 7, 5, 10]
# Initializing k
k = 6
# Printing original list
print ("The original list is : " + str(test_list))
# Using naive method
# to find smallest number
# greater than K
min_val = 10000000
for i in test_list :
if min_val > i and i > k :
min_val = i
# Printing result
print ("The minimum value greater than 6 is : " + str(min_val))
输出 :
The original list is : [1, 4, 7, 5, 10]
The minimum value greater than 6 is : 7
方法 #2:使用min()
+ 生成器表达式min()
返回序列中的最小数字并将其与生成器表达式耦合可以以非常简洁的方式执行此任务,因此在需要节省时间时更有用。
# Python3 code to demonstrate
# smallest number greater than K
# using min() + generator expression
# Initializing list
test_list = [1, 4, 7, 5, 10]
# Initializing k
k = 6
# Printing original list
print ("The original list is : " + str(test_list))
# Using min() + generator expression
# to find smallest number
# greater than K
min_val = min(i for i in test_list if i > k)
# Printing result
print ("The minimum value greater than 6 is : " + str(min_val))
输出 :
The original list is : [1, 4, 7, 5, 10]
The minimum value greater than 6 is : 7
方法 #3 : min() + filter()
与上述方法类似的方法,只是为了过滤列表中大于 k 的数字,在这种方法中使用filter()
而不是生成器表达式。以与上述类似的方式工作。
# Python3 code to demonstrate
# smallest number greater than K
# using min() + filter()
# Initializing list
test_list = [1, 4, 7, 5, 10]
# Initializing k
k = 6
# Printing original list
print ("The original list is : " + str(test_list))
# Using min() + filter()
# to find smallest number
# greater than K
min_val = min(filter(lambda i: i > k, test_list))
# Printing result
print ("The minimum value greater than 6 is : " + str(min_val))
输出 :
The original list is : [1, 4, 7, 5, 10]
The minimum value greater than 6 is : 7
方法 #4:使用sort() + bisect_right()
bisect_right()
加上sort()
为我们执行二进制搜索的任务,因此是解决此问题的好选择。 bisect_right()
因为它返回严格更大的数字,而不是数字本身(如果它存在于列表中)。
# Python3 code to demonstrate
# smallest number greater than K
# using sort() + bisect_right()
from bisect import bisect_right
# Initializing list
test_list = [1, 4, 7, 5, 10]
# Initializing k
k = 6
# Printing original list
print ("The original list is : " + str(test_list))
# Using sort() + bisect_right()
# to find smallest number
# greater than K
test_list.sort()
min_val = test_list[bisect_right(test_list, k)]
# Printing result
print ("The minimum value greater than 6 is : " + str(min_val))
输出 :
The original list is : [1, 4, 7, 5, 10]
The minimum value greater than 6 is : 7