Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

2D 배열에서 k' 가장 작은 요소를 찾는 Python 프로그램

<시간/>

하나의 n×n 사용자 입력 정수 행렬과 k 값이 제공됩니다. 우리의 임무는 2D 배열에서 k' 가장 작은 요소를 찾는 것입니다. 여기서 우리는 파이썬에서 heapq mudule.Heap 큐(또는 heapq)를 사용합니다. Python에서는 "heapq" 모듈을 사용하여 사용할 수 있습니다. 파이썬에서 이 모듈의 기술은 가장 작은 힙 요소가 팝될 때마다(최소 힙)입니다. 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