সমস্যা
একটি ইন্টিজার লিস্ট থেকে শীর্ষ N বড় এলিমেন্টগুলো বের করা।
Input: [40, 5, 10, 20, 9], N = 2
Output: [40, 20]
পদ্ধতি ১: সর্টিং (O(n log n))
def n_largest_sort(lst, n):
return sorted(lst, reverse=True)[:n]
print(n_largest_sort([40, 5, 10, 20, 9], 2)) # [40, 20]
পদ্ধতি ২: heapq.nlargest (O(n log k)) — বড় লিস্টের জন্য দক্ষ
import heapq
def n_largest_heap(lst, n):
return heapq.nlargest(n, lst)
print(n_largest_heap([40, 5, 10, 20, 9], 2)) # [40, 20]
পদ্ধতি ৩: ম্যানুয়াল সিলেকশন (O(n×k)) — শিক্ষামূলক
def n_largest_manual(lst, n):
result = []
temp = lst.copy()
for _ in range(min(n, len(temp))):
max_val = max(temp)
result.append(max_val)
temp.remove(max_val)
return result
print(n_largest_manual([12, 61, 41, 85, 40, 13, 77, 65, 100], 4))
# [100, 85, 77, 65]
পদ্ধতি ৪: numpy.partition (O(n)) — খুব বড় অ্যারে için
import numpy as np
arr = np.array([40, 5, 10, 20, 9])
n = 2
# partition: n-তম বড় এলিমেন্ট সঠিক পজিশনে, বামে ছোট, ডানে বড়
top_n = np.partition(arr, -n)[-n:]
top_n_sorted = np.sort(top_n)[::-1]
print(top_n_sorted) # [40 20]
পারফরম্যান্স তুলনা
| পদ্ধতি | টাইম কমপ্লেক্সিটি | স্পেস | ব্যবহার |
|---|---|---|---|
| sorted() | O(n log n) | O(n) | ছোট/মাঝারি লিস্ট, সরল |
| heapq.nlargest | O(n log k) | O(k) | বড় লিস্ট, k << n হলে সেরা |
| manual | O(n×k) | O(n) | শুধু লার্নিংয়ের জন্য |
| numpy.partition | O(n) | O(n) | বড় NumPy অ্যারে, হাই পারফরম্যান্স |
N ছোট এলিমেন্ট (nsmallest)
import heapq
print(heapq.nsmallest(3, [40, 5, 10, 20, 9])) # [5, 9, 10]