Python - 大于 K 的第 N 小数


本题要求使用 Python 查找大于 K 的第 N 小数。我们可以结合迭代和排序技术来查找所需元素。

理解问题

问题是要使用 Python 查找大于数字 K 的第 N 小数。基本上,我们需要找到一个大于 K 的数字,并且它是排序列表中从数字 K 开始的第 N 个数字。例如,我们将借助下图来理解这种现象:

方法 1:算法

在这种方法中,我们将构造一个方法,在这个方法中我们将传递三个参数:数字列表、值 K 和整数 N。此函数将过滤掉大于 K 的数字,然后将数字按升序排序。然后,函数将检查过滤后的列表中是否有 N 个数字,如果是,则返回第 N 小的数字。

  • 步骤 1 - 首先初始化数字列表以及 K 和 N 的值。

  • 步骤 2 - 接下来,我们将定义一个函数来查找应该大于 K 的第 N 小数。将此函数命名为 get_Nth_smallest,并在函数内部传递 num_list、K 和 N 作为输入。

  • 步骤 3 - 现在过滤给定 num_list 中大于 K 的数字。

  • 步骤 4 - 过滤数字后,我们将使用 sorted 方法对剩余数字进行排序。

  • 步骤 5 - 排序数字后,我们将检查剩余数字列表的长度,如果它小于 N,则返回 None。否则,返回排序列表中的第 N 个数字。

示例

# Initialize the list and variables
num_list = [2, 6, 4, 7, 8, 10, 15, 9]
K = 5
N = 3
# Define the function to get Nth smallest greater than K
def get_Nth_smallest(num_list, K, N):
   filter_nums = [num for num in num_list if num > K]
   sorted_num_list = sorted(filter_nums)
   if len(sorted_num_list) < N:
      return None  
   
   return sorted_num_list[N-1]
# Call the above function
Output = get_Nth_smallest(num_list, K, N)
# Print the Output
print(f"{N} smallest number greater than {K} is: {Output}")

输出

3 smallest number greater than 5 is: 8

复杂度

使用 Python 查找大于 K 的第 N 小数的时间复杂度为 O(N log N),其中 N 是给定 num_list 中的项目数。在代码中,我们过滤了数字,这需要 O(N) 时间。然后我们执行排序操作,这需要 O(N log N) 时间。然后,我们在排序列表中检查了第 N 小的数字,这需要 O(1) 时间。因此,总时间复杂度为 O(N log N)。

方法 2:算法

在这种方法中,我们将使用带 lambda 函数的 filter 方法来获得所需的结果。

  • 步骤 1 - 首先初始化变量 num_list、K 和 N。

  • 步骤 2 - 定义一个函数来查找应该大于 K 的第 N 小数,并将此函数命名为 get_Nth_smallest(),并传递 num_list、K 和 N 作为输入。

  • 步骤 3 - 现在使用 filter 和 lambda 函数过滤给定 num_list 中大于 K 的数字。

  • 步骤 4 - 过滤数字后,我们将使用 sorted 方法对剩余数字进行排序。

  • 步骤 5 - 返回第 (N - 1) 个项目作为结果。

示例

# Initialize the list and variables
num_list = [2, 6, 4, 7, 8, 10, 15, 9]
K = 9
N = 2

# Define the function to get Nth smallest greater than K
def get_Nth_smallest(num_list, K, N):
   result = list(filter(lambda a: a > K, num_list))
   result.sort()
   return result[N-1]
   
# Call the above function
Output = get_Nth_smallest(num_list, K, N)
print(f"{N} smallest number greater than {K} is: {Output}")

输出

2 smallest number greater than 9 is: 15

结论

我们已经成功地实现了使用 Python 查找大于 K 的第 N 小数的解决方案。我们使用了非常高效的逻辑来获得所需的结果。当我们需要从大型数据中查找键或数据,并且不知道第 N 个元素时,这个问题会很有帮助。

更新于:2023年10月17日

81 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.