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

목록에서 N개의 가장 큰 요소를 찾는 Python 프로그램

<시간/>

주어진 정수 목록에서 우리의 임무는 목록에서 가장 큰 N개의 요소를 찾는 것입니다.

예시

Input : [40, 5, 10, 20, 9]
N = 2
Output: [40, 20]

알고리즘

Step1: Input an integer list and the number of largest number.
Step2: First traverse the list up to N times.
Step3: Each traverse find the largest value and store it in a new list.

예시

def Nnumberele(list1, N):
   new_list = []
   for i in range(0, N):
      max1 = 0
   for j in range(len(list1)):
      if list1[j] > max1:
         max1 = list1[j];
         list1.remove(max1);
         new_list.append(max1)
      print("Largest numbers are ",new_list)
      # Driver code
      my_list = [12, 61, 41, 85, 40, 13, 77, 65, 100]
      N = 4
      # Calling the function
Nnumberele(my_list, N)

출력

Largest numbers are [100, 85, 77, 65]