Home > Mobile >  I have a list inside it there are tuples with names and marks of students i want to select studrnts
I have a list inside it there are tuples with names and marks of students i want to select studrnts

Time:12-29

this is the list:

l1=[('arjun',21),
    ('arushi',22),
    ('aman',22),
    ('tanmai',23)]

and i have a program which will find out the second highest marks which is 22 (i somehow made it). Now i want to print out the names which correspond to the marks = 22 and I'm unable to do it. So basically for the above list the output should be

arushi aman

CodePudding user response:

with a list of tuples , you can find the second highest element by sorting the list based on the second value of the tupl

l1=[('arjun',21),
    ('arushi',22),
    ('aman',22),
    ('tanmai',23)]

l1.sort(key = lambda x: x[1])
l1.reverse()
second_highest_marks = l1[1][1]
for item in l1:
    if(item[1]==second_highest_marks):
        print(item[0])

This code first sorts the list and then prints all the elements with the same marks as the second highest

if you are worried about the time complexity , then the python sort function is O(nlogn)

CodePudding user response:

Track the names while you check for the second highest value.

l1=[('arjun',21), ('arushi',22), ('aman',22), ('tanmai',23)]

first_2_largest = [[[], 0], [[], 0]]

for mark in l1:
    if mark[1] == first_2_largest[0][1]:
        first_2_largest[0][0].append(mark[0])
    elif mark[1] == first_2_largest[1][1]:
        first_2_largest[1][0].append(mark[0])
    elif mark[1] > first_2_largest[0][1]:
        first_2_largest.insert(0, [[mark[0]], mark[1]])
        first_2_largest.pop()
    elif mark[1] > first_2_largest[1][1]:
        first_2_largest.pop()
        first_2_largest.append([[mark[0]], mark[1]])
        
print(', '.join(first_2_largest[-1][0]))

Output

arushi, aman

Also post your code/snippet along with your questions & errors, so that others can easily understand and help better.

  • Related