How to find the rank of students respective of their marks

Question:

I have an array of marks with N no of Entries. I have to find the rank of the student according to the marks i.e. if 2 students have same marks then they have same rank.

y=0
for x in marks:
 if marks[N] > marks[N+1]:
  rank=rank+1
 if marks[N] == marks[N+1]:
  rank=rank
  y=y+1

It is the logic i am trying to use in this but didn’t get the required answer

For example :

marks = [89,88,79,74,74,74,74,74,64,56,56,25,24]

SO the rank should be like

score   rank
89      1
88      2
79      3
74      4
74      4
74      4
74      4
74      4
64      9

and so on .

Asked By: Sahil Sharma

||

Answers:

welcome to StackOverflow. I’ve tried to answer in a way that mirrors the logic you described above. But looking at the code you supplied I would suggest reading up on some basic Python tutorials. Happy coding!

marks = [89,88,79,74,74,74,74,74,64,56,56,25,24]
current_rank = 0
global_rank = 0
current_mark = 0

for mark in marks:
    global_rank += 1
    if mark != current_mark:
        current_mark = mark
        current_rank = global_rank
    print(current_mark, current_rank)
Answered By: Marvin van Aalst

Assuming the list marks is already sorted, you can pair adjacent marks by zipping the list with itself but with an offset of 1, and keep appending the same rank as the last rank if the adjacent marks are the same, or else append the length of the current ranks list plus 1:

ranks = [1]
for a, b in zip(marks, marks[1:]):
    ranks.append(ranks[-1] if a == b else len(ranks) + 1)
print(ranks)

This outputs:

[1, 2, 3, 4, 4, 4, 4, 4, 9, 10, 10, 12, 13]
Answered By: blhsing

Students roll no to be auto generated

num = 1

def roll():
    global num
    num += 1
    return num
Answered By: sitesh bade
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.