python找出数组的最小元素,Python程序在2D数组中找到第k个最小元素

该博客介绍了如何在Python中使用heapq模块寻找二维数组的第k小元素。首先创建一个二维数组,然后将第一行转换为最小堆,遍历其余行并将元素推入堆中。最后,通过heapq.nsmallest()方法获取前k个最小元素,并打印第k个元素。示例展示了如何处理一个4x4的矩阵并找到第10小的元素,结果为40。
摘要由CSDN通过智能技术生成

给出一个n×n用户输入整数矩阵,值k。我们的任务是找出二维数组中第k个最小的元素。在这里,我们在Python中使用了heapq mudule.Heap队列(或heapq)。在Python中,可以使用“ heapq”模块使用。python中此模块的技术是每次弹出最小的堆元素(最小堆)。nsmallest()方法用于从数据帧或序列中获取n个最小值。

示例Input Array is::

10 20 20 40

15 45 40 30

32 33 30 50

12 78 99 78

The value of k is 10

10 th smallest element is 40

算法Step 1: First create a 2D array.

Step 2: Then assign first row to a variable and convert it into min heap.

Step 3: Then traverse remaining rows and push elements in min heap.

Step 4: Now use nsmallest(k, iterable) method of heapq module and get list of first k smallest element, nsmallest(k,list) method returns first k smallest element now print last element of that list.

范例程式码# python program to find K'th smallest element in

# a 2D array in Python

import heapq

def smallestele(A):

assignval = A[0]

heapq.heapify(assignval)

for i in A[1:]:

for j in i:

heapq.heappush(assignval,j)

mini = heapq.nsmallest(k,assignval)

print (k,"th smallest element is ",mini[-1])

# Driver program

if __name__ == "__main__":

A=[]

n=int(input("Enter N for N x N matrix : "))      #3 here

#use list for storing 2D array

#get the user input and store it in list (here IN : 1 to 9)

print("Enter the element ::>")

for i in range(n):

row=[]                                        #temporary list to store the row

for j in range(n):

row.append(int(input()))                   #add the input to row list

A.append(row)                                 #add the row to the list

print(A)

# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display the 2D array

print("Display Array In Matrix Form")

for i in range(n):

for j in range(n):

print(A[i][j], end=" ")   print()                                       #new line

k = int(input("Enter the kth position ::>"))

smallestele(A)

输出结果Enter N for N x N matrix : 4

Enter the element ::>

10

20

20

40

15

45

40

30

32

33

30

50

12

78

99

78

[[10, 20, 20, 40], [15, 45, 40, 30], [32, 33, 30, 50], [12, 78, 99, 78]]

Display Array In Matrix Form

10 20 20 40

15 45 40 30

32 33 30 50

12 78 99 78

Enter the kth position ::>10

10 th smallest element is 40

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值