簡體   English   中英

Python算法在未排序的數組中找到k個最小數字的索引?

[英]Python algorithm to find the indexes of the k smallest number in an unsorted array?

是否有任何算法可以在python的未排序數組中找到k個最小數字的索引? 我知道如何使用numpy模塊來實現此目的,但是我沒有在尋找。 我立即想到的一個方向是必須使用排序算法。 所以可以說我有一種算法可以使用冒泡排序在python中對數組進行排序:

def bubbleSort(arr):
n = len(arr)

# Traverse through all array elements
for i in range(n):

    for j in range(0, n-i-1):
        # Swap if the element found is greater
        # than the next element
        if arr[j] > arr[j+1] :
            arr[j], arr[j+1] = arr[j+1], arr[j]

我不確定如何修改此算法以僅返回數組中k個最小數字的索引。 使用排序算法或選擇算法(如quickselect,quicksort)的任何幫助都將受到贊賞。

編輯1:所以說數組是:

a = [12, 11, 0, 35, 16, 17, 23, 21, 5]

然后,它必須僅返回一個數組: index_of_least_k = [2,8,1]

對於k = 3。

如果必須修改排序算法(例如冒泡排序),那么我將了解如何進行更改,以便這次可以交換索引,例如:

def modified_bubbleSort(arr, index):
      n = len(arr)

      # Traverse through all array elements
      for i in range(n):

           for j in range(0, n-i-1):
                  # Swap if the element found is greater
                  # than the next element
                  if arr[j] > arr[j+1] :
                         index[j], index[j+1] = index[j+1], index[j]
      return index


array = [12, 11, 0, 35, 16, 17, 23, 21, 5]
index = [0, 1, 2, 3, 4, 5, 6, 7, 8]

indexOfAllsorted = modified_bubblesort(array, index)

在這種情況下,它返回我:

indexOfAllsorted = [2,8,1,0,4,5,7,6]

我不希望這樣,因為有額外的5個值,為避免內存開銷,我的算法應該只有:

index_of_least_k = [0, 0, 0]

在內存中為k = 3,然后將其填充。 我希望我說清楚了。

EDIT2:我沒有尋找任何庫或模塊來在python中完成該任務。

您可以使用heapq.nsmallest從可迭代heapq.nsmallest中獲取n最小的項。 那么,如何創建一個可迭代的變量,以測量輸入的值,但返回其索引呢? 一種方法是使用enumerate函數獲取(index, value)對的可迭代,然后使用鍵函數僅使用值。

from heapq import nsmallest
from operator import itemgetter

def indices_of_n_smallest(n, seq):
    smallest_with_indices = nsmallest(n, enumerate(seq), key=itemgetter(1))
    return [i for i, x in smallest_with_indices]

array = [12, 11, 0, 35, 16, 17, 23, 21, 5]
indices_of_n_smallest(3, array)
# [2, 8, 1]

這是關於氣泡排序的事情。 每次內部循環完成迭代時,都會精確找到一個元素的正確位置。 例如,您的代碼每次都會找到第i個最大元素,因為它以升序排序。 讓我們將>符號翻轉為<; 現在,每次j循環結束時,它將找到第i個最小元素。 因此,如果在i = k時停止排序,則將有k個最小的元素。

def modified_bubbleSort(arr, index, k):
  n = len(arr)
  ans = []

  for i in range(k):

       for j in range(0, n-i-1):
              # Swap if the element found is smaller
              # than the next element
              if arr[index[j]] < arr[index[j+1]] :
                     index[j], index[j+1] = index[j+1], index[j]
       ans.append(index[n-i-1])
  return ans

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM