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)输出结果
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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便