Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để tìm vị trí của phần tử tối đa và tối thiểu trong danh sách?

Trong python rất dễ dàng để tìm ra phần tử tối đa, tối thiểu và cả vị trí của chúng. Python cung cấp các hàm sẵn có khác nhau. min () được sử dụng để tìm ra giá trị nhỏ nhất trong một mảng, max () được sử dụng để tìm ra giá trị lớn nhất trong một mảng. index () được sử dụng để tìm chỉ mục của phần tử.

Thuật toán

maxminposition(A, n)
/* A is a user input list and n is the size of the list.*/
Step 1: use inbuilt function for finding the position of minimum element.
            A.index(min(A))
Step 2: use inbuilt function for finding the position of a maximum element.
            A.index(max(A))

Mã mẫu

# Function to find minimum and maximum position in list
def maxminposition(A, n):
   # inbuilt function to find the position of minimum 
   minposition = A.index(min(A))
   # inbuilt function to find the position of maximum 
   maxposition = A.index(max(A)) 
   print ("The maximum is at position::", maxposition + 1) 
   print ("The minimum is at position::", minposition + 1)
# Driver code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
maxminposition(A,n)

Đầu ra

Enter the size of the List ::4
Enter the Element::
12
34
1
66
The maximum is at position:: 4
The minimum is at position:: 3