0

this program is to find the second largest number this works for most of the inputs but it is not working for the following inputs.

n=4
a1 = '-7 -7 -7 -7 -6'
a1=[int(arr_temp) for arr_temp in a1.strip().split(' ')]
print(a1)
largest = max(a1)
largest2 = 0
for i in range(0,len(a1)):
    if ((a1[i]>largest2 or a1[i]<0) and largest2<largest and    a1[i]!=largest):
        largest2 = a1[i]
print(largest2)
Community
  • 1
  • 1
el2e10
  • 1,518
  • 22
  • 22

1 Answers1

1

Setting largest2 to 0 just complicates the if statement later. Set it to the smallest value in the array and it becomes clearer.

n=4
a1 = '-7 -7 -7 -7 -6'
a1=[int(arr_temp) for arr_temp in a1.strip().split(' ')]
print(a1)
largest = max(a1)
largest2 = min(a1)

for i in range(0,len(a1)):
    if (a1[i] > largest2) and (a1[i] < largest):
    largest2 = a1[i]

print(largest2)

Note that if the array is large, the call to min becomes non-trivial. In that case you could set largest2 to the smallest value possible (on that note, this link might be useful)

Community
  • 1
  • 1
dazedandconfused
  • 3,131
  • 1
  • 18
  • 29
  • thanks for the info.i don't have enough reputation thats why my up vote is not being shown. – el2e10 Nov 04 '16 at 07:08