Finding third largest element in the list without using len() and sort()

Question:

Here is the code which I used to find the third largest element in the list without using any built in functions like max,sort,len.

list = [12, 45, 2, 41, 31, 10, 8, 6, 4]
#list = [35,10,45,9,8,5]
largest_1 = list[0]
largest_2 = list[0]
largest_3 = list[0]
print (largest_1)
print (largest_2)
print (largest_3)
for each in list:
    print ('Each element Before if Loop --->',each)
    if each > largest_1:
        print ('Each element inside if loop --->',each)
        largest_1 = each
        print('largest_1 element---->',largest_1)
    elif largest_2 != largest_1 and largest_2 < each:
        print ('Each element inside if loop --->',each)
        largest_2 = each 
        print ('Largest_1 element is ---->',largest_1)
        print ('Largest_2 element is ---->',largest_2)
    elif largest_3 != largest_2  and largest_3 < each:
        print ('Each element inside if loop --->',each)
        largest_3 = each
        print ('Largest_2 element is ---->',largest_2)
        print ('Largest_3 element is ---->',largest_3)

print (largest_1)
print (largest_2)
print (largest_3)

The same code is not working for the

list = [35,10,45,9,8,5]

I am not getting what mistake I have done. How can I fix this?

Asked By: venkat

||

Answers:

I don’t know why you wouldn’t want to use len(), or max() – they’re literally built-in functions, not part of any library, and there’s no practical reason not to use them. That said, if you really want to do it otherwise, here’s another approach:

Take three variables, assign them largest, second_largest, and third_largest, and walk through the list.

largest = 0
second_largest = 0
third_largest = 0

for each in list:
    if each >= largest:
        # assign the new largest, and push the rest of them back down the chain
        # we use >= instead of > to ensure that duplicate maximums still work.
        #   
        largest, second_largest, third_largest = each, largest, second_largest
    elif each >= second_largest:
        second_largest, third_largest = each, second_largest
    elif each > third_largest:
        third_largest = each
print(third_largest)
Answered By: Green Cloak Guy

You could also store your top 3 max numbers in a dictionary, then print out the third largest one:

largest = {"first": 0, "second": 0, "third": 0}

lst = [12, 45, 2, 41, 31, 10, 8, 6, 4]

for number in lst:
    if number > largest["first"]:
        largest["third"] = largest["second"]
        largest["second"] = largest["first"]
        largest["first"] = number
    elif number > largest["second"]:
        largest["third"] = largest["second"]
        largest["second"] = number
    elif number > largest["third"]:
        largest["third"] = number

print(largest)
# {'first': 45, 'second': 41, 'third': 31}

print(largest["third"])
# 31
Answered By: RoadRunner

@venkat: Here another proposal to get the third largest number out of your list without using len() and sort().

def find_largest(alist):
    """
    Find the largest number in a list.

    Return the largest number found and it index
    """
    largest = alist[0]
    for item in alist[1:]:
        if item > largest:
            largest = item

    idx =  alist.index(largest)
    return (idx, largest)

#--
def get_third_largest(alist):
    """
    Return the third largest number in a list.
    """
    # Let make a copy of the input list so that any change to it may not affect the
    # original data.
    thisList = alist.copy()

    index, largest = 0, 0
    for item in range(3):
        index, largest = find_largest(thisList)
        if item != 2:
            # delete the first two largest from the List
            del thisList[index]
    return largest

# Test of the algorithm
if __name__ == "__main__":
    List = [12, 45, 2, 41, 31, 10, 8, 6, 4]
    third = get_third_largest(List)
    # print("Initial list: ", List)
    # print("The third largest item in the list:")
    print("tExpected: 31")
    print("tResult:   %d" % third);

# --- Output---
# Expected: 31
# Result:   31
Answered By: eapetcho
list = [12, 45, 2, 41, 31, 10, 8, 6, 4]
c = 0
for i in list:
  c+=1
  for j in range(c):
      for k in range(j):
          if list[j] > list[k]:
              list[j], list[k] = list[k],list[j]
          else:
              list[j],list[k] = list[j],list[k]
print(list[2]," is the third largest element")
Answered By: Dharavath Ramdas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.