简体   繁体   English

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

[英]Finding the Kth Largest element in a Python List using recursion

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.给定一个包含一些随机未排序数字的输入列表,我正在尝试编写一个程序来输出该列表中第 k 个最大的不同元素。 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

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 作为输入,并使用小于主元的所有元素填充列表“较小”,并使用大于主元的所有元素填充另一个“更大”列表。

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.现在,查看两个列表的长度,我可以确定第 k 个最大的元素是在较小的列表中还是在较大的列表中。 Now I recursively call the same function.现在我递归地调用相同的函数。 However, my program's output is wrong for certain values of k.但是,对于某些 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

Is there any reason you want to use recursion? 你有什么理由想使用递归吗? To find the kth largest element of a list you have to look through the entire list, so the problem is essentially O(n) complexity anyway. 要查找列表中第k个最大元素,您必须查看整个列表,因此问题本质上是O(n)复杂度。

You could do this without recursion like this: 你可以这样做而不会像这样递归:

el = [10, 10, 53, 20, 30, 40, 59, 40]
k = 2

def kth_largest(input_list, k):
    # initialize the top_k list to first k elements and sort descending
    top_k = input_list[0:k]
    top_k.sort(reverse = True)

    for i in input_list[k:]:
        if i > top_k[-1]:
            top_k.pop() # remove the lowest of the top k elements
            top_k.append(i) # add the new element
            top_k.sort(reverse = True) # re-sort the list

    return top_k[-1] # return the kth largest


kth_largest(el, k)

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))

Here is a simple solution: 这是一个简单的解决方案:

def kthmax(k, list):
    if (k == 1):
        return max(list)
    else:
        m = max(list)
        return(kthmax(k-1, [x for x in list if x != m]))

kthmax(3,[4, 6, 2, 7, 3, 2, 6, 6])

Output: 4 产量:4

Algorithm: Take the index of max value and convert to zero. 算法:取最大值的索引并转换为零。

def high(arr,n):
    for i in range(n+ 1 ):
        arr[arr.index(max(arr))] = 0
        return max(arr)
high([1,2,3,4,5], 2)

If we can pass in a list or series that is already sorted in descending order, eg 如果我们可以传入已经按降序排序的列表或系列,例如

el.sort_values(ascending=False, inplace = True) 

then you can easily find the kth largest (index,value) tuple using just simple slicing of sorted dataframe column and/or list 然后你可以使用简单的排序数据帧列和/或列表的切片轻松找到第k个最大(索引,值)元组

def kth_largest(input_series, k):
    new_series = input_series[k-1:len(input_series)]
    return (np.argmax(new_series) , np.max(new_series))

el = pd.Series([10, 10, 53, 20, 30, 40, 59, 40])
print el
k = 2

el.sort_values(ascending=False, inplace=True)

print kth_largest(el, 2)

Output: 30
0    10
1    10
2    53
3    20
4    30
5    40
6    59
7    40
dtype: int64
(2, 53)

My way of finding the Kth largest element is...我找到第 K 个最大元素的方法是......

lst=[6,2,3,4,1,5]
print(sorted(lst,reverse=True)[k-1])

在 S Rohith Kumar 的回答之上,如果输入有重复值,那么答案可以是:

print(sorted(set(lst),reverse=True)[k-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM