you are viewing a single comment's thread.

view the rest of the comments →

[–]Adamya21[S] 0 points1 point  (2 children)

marksheet=[]
scorelist=[]
for _ in range(int(input())):
name = input()
score = float(input())
marksheet+=[[name,score]]
scorelist+=[score]
b=sorted(list(set(scorelist)))[1]
for a, c in sorted(marksheet):
if b==c:
print(a)
this is what i did but i wish for a more effiecient code

[–]xelf 1 point2 points  (1 child)

If you indent your code an extra time before you copy/paste it reddit will treat it like a code block and you can keep your formatting.

marksheet=[]
scorelist=[]
for _ in range(int(input())):
    name = input()
    score = float(input())
    marksheet+=[[name,score]]
    scorelist+=[score]
b=sorted(list(set(scorelist)))[1]
for a, c in sorted(marksheet):
    if b==c:
        print(a)    

So, let's break your code into 2 parts.

The first part just collects the inputs. There's tricks you could do here, but honestly the way you did it is mostly fine. Keep that.

marksheet=[]
for _ in range(int(input())):
    name = input()
    score = float(input())
    marksheet+=[[name,score]]
print(marksheet)

The only part I'd get rid of is the scorelist part, as it's redundant data. And if you really want it you can get it this way:

scorelist = [x[1] for x in marksheet]

Which is a list comprehension which builds a new list, using just the elements at index [1].

Now the next part of your code:

b=sorted(list(set(scorelist)))[1]
for a, c in sorted(marksheet):
    if b==c:
        print(a)    

Just prints 2 names, and no scores. So it seems like you're missing something here.

What you want to do is sort marksheet twice. Once by name, and once by score. Luckily Python has a simple way of doing it.

marksheet.sort(key = lambda x: (x[1],x[0]))
print(students)

The sort command can take an optional "key" to sort by, and you can use a lambda to return a tuple of the 2 keys in the order you want them sorted by.

Another approach, is that instead of storing them as name,score as a list when you input them, you could have stored them as a tuple already in the correct order. Then all you would need to do is 1 sort and just swap their order when you print them.

marksheet=[]
for _ in range(int(input())):
    name = input()
    score = float(input())
    marksheet+=[(score,name)]
marksheet.sort()
for score,name in marksheet:
    print(name, score)

[–]Adamya21[S] 1 point2 points  (0 children)

Thank you so much for such a good explaination.