[英]Finding the Kth Largest element in a Python List using recursion
給定一個包含一些隨機未排序數字的輸入列表,我正在嘗試編寫一個程序來輸出該列表中第 k 個最大的不同元素。 例如:
Input:
el = [10,10, 20,30,40, 40]
k = 2
Output: 30 #Since 30 is the second largest distinct element in the list
以下函數將列表、主元索引和 k 作為輸入,並使用小於主元的所有元素填充列表“較小”,並使用大於主元的所有元素填充另一個“更大”列表。
現在,查看兩個列表的長度,我可以確定第 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
你有什么理由想使用遞歸嗎? 要查找列表中第k個最大元素,您必須查看整個列表,因此問題本質上是O(n)復雜度。
你可以這樣做而不會像這樣遞歸:
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)
使用遞歸有一種簡單的方法來解決這個問題。 我只是不確定為什么你需要問題描述中的樞軸...例如:
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))
這是一個簡單的解決方案:
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])
產量:4
算法:取最大值的索引並轉換為零。
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)
如果我們可以傳入已經按降序排序的列表或系列,例如
el.sort_values(ascending=False, inplace = True)
然后你可以使用簡單的排序數據幀列和/或列表的切片輕松找到第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)
我找到第 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.