So I have to find the second largest number from list. I am doing it through simple loops.
My approach is to divide a list into two parts and then find the largest n
alist = [-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
largest = 0
second_largest = 0
for large in alist:
if second_largest < large:
second_largest = large
if largest < large:
temp = second_largest
second_largest = largest
largest = temp
print "First Highest:- %s" %largest
print "Second Highest:- %s" %second_largest
Here is my program, irrespective of complexity
if __name__ == '__main__':
alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
alist1 = [ ]
[alist1.append(x) for x in alist if x not in alist1]
alist1.sort()
print alist1[-2]
alist=[10, 0,3,10,90,5,-2,4,18,45,707, 100,1,-266,706, 1]
print(max(alist))
second_largest=alist[0]
for i in range(len(alist)):
if (alist[i]>second_largest and alist[i]!=max(alist)):
second_largest=alist[i]
print(second_largest)
Try this:
alist=[10, 0,3,10,90,5,-2,4,18,45,707, 100,1,-266,706, 1]
largest = alist[0]
second_largest = alist[0]
for i in range(len(alist)):
if alist[i] > second_largest:
second_largest = alist[i]
if alist[i] > largest:
tmp = second_largest
second_largest = largest
largest = tmp
print(largest, second_largest)
O(n) solution
alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
m = alist[:2] #m will hold 2 values, fill it with the first two values of alist
for num in alist:
m = sorted(m + [num],reverse=True)[:2] #appends num to m and sorts it, takes only top 2
m[1] #the second highest element.
EDIT: changed to work with negative numbers. Basic description as follows
First I set m to be the first two elements of alist. As I iterate through alist I will be adding one value to the end of m, then sorting the three elements and throwing away the smallest one. This ensures that at the end m will contain the top two largest elements.
alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
sorted_list = sorted(set(alist))
sorted_list.pop()
print(max(sorted_list))