Python 程序查找列表中的最大值、最小值、第二大值和第二小值?


给出数组后,我们需要找出最大值、最小值、第二大值和第二小值。

算法

Step 1: input list element
Step 2: we take a number and compare it with all other number present in the list.
Step 3: get maximum, minimum, secondlargest, second smallest number.

示例代码

# To find largest, smallest, second largest and second smallest in a List
   def maxmin(A):
      maxi = A[0]
      secondsmax = A[0]
      mini = A[0]
      secondmini = A[0]
      for item in A:
   if item > maxi:
      maxi = item
   elif secondsmax!=maxi and secondsmax < item:
      secondsmax = item
   elif item < mini:
      mini = item
   elif secondmini != mini and secondmini > item:
      secondmini = item
      print("Largest element is ::>", maxi)
      print("Second Largest element is ::>", secondsmax)
      print("Smallest element is ::>", mini)
      print("Second Smallest element is ::>", secondmini)
# Driver Code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the number ::")
for i in range(int(n)):
k=int(input(""))
A.append(int(k))
maxmin(A)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

Enter the size of the List ::6
Enter the number ::
12
30
2
34
90
67
Largest element is ::> 90
Second Largest element is ::> 67
Smallest element is ::> 2
Second Smallest element is ::> 12

更新于: 2020 年 6 月 23 日

2 千次 + 浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告