Skip to content

Instantly share code, notes, and snippets.

@ashwch
Last active December 14, 2015 07:48
Show Gist options
  • Select an option

  • Save ashwch/5052943 to your computer and use it in GitHub Desktop.

Select an option

Save ashwch/5052943 to your computer and use it in GitHub Desktop.
Program to find second largest element in a list
"""
Program to find second largest element in a list
"""
def second_max(lis):
if len(lis)==0:
return 'empty list'
if len(lis)==1:
return 'Only 1 item in the list'
if lis[1]>lis[0]:
maxx,smaxx=lis[1],lis[0]
elif lis[0]>lis[1]:
maxx,smaxx=lis[0],lis[1]
else:
maxx=lis[0]
smaxx=-float('inf')
for x in lis[2:]:
if x>maxx:
smaxx=maxx
maxx=x
elif smaxx<x<maxx:
smaxx=x
print smaxx if smaxx !=-float('inf') else 'NO smaxx'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment