Skip to content

Commit

Permalink
Add sorting challenge comparator
Browse files Browse the repository at this point in the history
  • Loading branch information
esl4m committed Jun 3, 2022
1 parent cb945da commit 703942b
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions InterviewPreparationKit/sort/comparator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from functools import cmp_to_key
class Player:
def __init__(self, name, score):
self.name = name
self.score = score

def __repr__(self):
pass

def comparator(a, b):
if a.score < b.score:
return 1
elif a.score > b.score:
return -1
else: # score are equal
if a.name > b.name:
return 1
elif a.name < b.name:
return -1
else:
return 0

n = int(input())
data = []
for i in range(n):
name, score = input().split()
score = int(score)
player = Player(name, score)
data.append(player)

data = sorted(data, key=cmp_to_key(Player.comparator))
for i in data:
print(i.name, i.score)

# Sample input
# 5
# amy 100
# david 100
# heraldo 50
# aakansha 75
# aleksa 150

# Sample Output
# aleksa 150
# amy 100
# david 100
# aakansha 75
# heraldo 50

0 comments on commit 703942b

Please sign in to comment.