In [1]:
import array as arr
def second(A, s):
m = A[0]
for i in range(0, s):
if m > A[i]:
m = A[i]
m1 = m
m2 = m
for i in range(0, s):
if A[i] > m1:
m2 = m1
m1 = A[i]
elif A[i] > m2 and m1 != A[i]:
m2 = A[i]
return m2
A = arr.array('i', [])
s = int(input('Enter the size of the array: '))
print ('Enter ', s, ' elements: ')
for i in range(0, s):
val = int(input())
A.append(val)
if s == 1:
print ('Only one element is present in the array')
else:
res = second(A, s)
print ('Second largest value of the array is: ', res)
Enter the size of the array: 5 Enter 5 elements: 10 5 6 5 6 Second largest value of the array is: 6
Finding the second largest by applying the sort() function
In [2]:
li = []
size = int (input('Enter the size of the list: '))
print ('Enter ', size, ' elements: ')
for i in range (0, size):
value = int (input ())
li.append(value)
li.sort()
li
second = li[-2] #Second but not unique
for i in range (size, 0): #Making second as the unique value
if second == li[i]:
continue
else:
second = li[i]
print ('Second largest is: ', second)
Enter the size of the list: 5 Enter 5 elements: 8 4 5 5 6 Second largest is: 6
No comments:
Post a Comment