使用递归查找 Python 列表中的第 K 个最大元素

编程入门 行业动态 更新时间:2024-10-28 07:26:36
本文介绍了使用递归查找 Python 列表中的第 K 个最大元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定一个包含一些随机未排序数字的输入列表,我正在尝试编写一个程序来输出该列表中第 k 个最大的不同元素.例如:

Given an input list that contains some random unsorted numbers, I am trying to write a program that outputs the kth largest distinct element in that list. For example:

Input: el = [10,10, 20,30,40, 40] k = 2 Output: 30 #Since 30 is the second largest distinct element in the list

以下函数将列表、主元索引和 k 作为输入,并使用小于主元的所有元素填充列表 "lesser" 并填充另一个列表 "greater" 包含所有大于主元的元素.

The following function, takes as input a list, the pivot Index and k and populates list "lesser" with all elements lesser than the pivot and populates another list "greater" with all elements greater than the pivot.

现在,查看两个列表的长度,我可以确定第 k 个最大的元素是在较小的列表中还是在较大的列表中.现在我递归地调用相同的函数.但是,对于某些 k 值,我的程序的输出是错误的.

Now, looking at the length of the two list, I can determine if the kth largest element is in the lesser list or the greater list. Now I recursively call the same function. However, my program's output is wrong for certain values of k.

def kthLargest(el, pivotIndex, k): pivot = el[pivotIndex] lesser = [] #List to store all elements lesser than pivot greater = [] #Lsit to store all elements greater than pivot equals = [] #List to store all elements equal to pivot for x in el: if x > pivot: greater.append(x) elif x < pivot: lesser.append(x) else: equals.append(x) g = len(greater) #Length of greater list l = len(lesser) if(g == k - 1): #If greater list has k-1 elements, that makes the pivot kth largest element return pivot elif(g < k): return kthLargest(lesser, l - 1, k) #If greater list is smaller than k, kth largest element is in lesser list else: return kthLargest(greater, g - 1, k) #Else kth largest element is in greater list

推荐答案

有一个简单的方法可以使用递归来解决这个问题.我只是不确定为什么您需要问题描述中的枢轴...例如:

There's an easy way to do this problem using recursion. I'm just not sure why you need the pivot in the problem description... For example:

def find_kth(k, arr): if k == 1: return max(arr) m = max(arr) new_arr = list(filter(lambda a: a != m, arr)) return(find_kth(k-1, new_arr))

更多推荐

使用递归查找 Python 列表中的第 K 个最大元素

本文发布于:2023-11-29 18:09:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647196.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   元素   列表中   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!