March 1, 2017
How to find second largest number in python
Second largest number python problem
Given an array of numbers, write python code to find second largest number in array
Code to find second largest number in list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Array A = [1, 5, 7, 5] # Initialize first and second maximum max1 = A[0] max2 = A[1] if A[1] < A[0]: max1 = A[1] max2 = A[0] # Find the first and second maximum for num in A: # if the current element is greater # than the first maximum then we # should update it if num >= max1 and num < max2: max1 = num # Otherwise compare the current element # with the second maximum and update it # similarly elif num >= max2: max1 = max2 max2 = num # Otherwise keep the first and # second maximum intact else: # Nothing pass # Print print "Second largest number is %d" % max1 |
A C++ version can also be found here.
Thanks for visiting. Please use the comments section for feedback.
More from my site
2 Comments
L=[ 4, 61, 72, 2, 5, 85, 3,1]
a = L[0]
b =L[1]
for i in range(1, len(L)):
if a < L[i]:
b= a
a = L[i]
print("2nd largest=", b)
L=[ 120,4, 99, 61, 72, 2, 5, 85, 3,77,100,1]
a = L[0]
b =L [1]
if a < b:
a, b = b, a
#print(a,b)
for i in range(2,len(L)):
if a < L[i]:
b= a
a = L[i]
else:
if b<L[i]:
b= L[i]
print("2nd largest=", b)