We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Sorting: Comparator
- Discussions
Sorting: Comparator
Sorting: Comparator
+ 8 comments It should have a super easy difficulty.
+ 8 comments In Python 3, I think the template code is incorrect. We can solve it by writing this
def comparator(a, b): if a.score < b.score: return 1 if a.score > b.score: return -1 if a.name < b.name: return -1 if a.name > b.name: return 1 return 0
However if the line
data = sorted(data, key=cmp_to_key(Player.comparator))
was changed to
data = sorted(data, key=Player.key)
we could solve it with the better
def key(self): return(-self.score, self.name)
We can use the second approach by dummying out the cmp_to_key function.
def cmp_to_key(key): return key class Player: def __init__(self, name, score): self.name = name self.score = score def comparator(self): return(-self.score, self.name)
+ 1 comment Simple Java implementation:
class Checker implements Comparator<Player> { @Override public int compare(Player a, Player b) { if(a.score != b.score) { return b.score - a.score; } return a.name.compareTo(b.name); } }
+ 3 comments Hi Team,
Can you also enable C# in editor for this problem
+ 3 comments class Player: def __init__(self, name, score): self.name = name self.score = score def __repr__(self): pass def comparator(a, b): val = b.score - a.score if val == 0: return -1 if a.name < b.name else 1 return val
Load more conversations
Sort 450 Discussions, By:
Please Login in order to post a comment