Program to find the final ranking of teams in order from highest to lowest rank in python

PythonServer Side ProgrammingProgramming

Suppose we have a list of strings called votes, here each entry is in lowercase letters and they are representing votes on candidates in order from highest to lowest preference. Here the rank of a candidate depends first by the number of votes received on the highest preference. Now if there are ties, we shall check the number of votes received on next highest preference, and so on. If there are still ties, then they will be ranked alphabetically. So we have to find the final ranking of the teams in order from highest to lowest ranked.

So, if the input is like votes = ["zyx", "zxy", "xyz"], then the output will be "zxy", as z received the most number of highest preference, so it is ranked first. Then x received the second most number of highest preference, and y didn't receive any highest preference votes.

To solve this, we will follow these steps −

  • count := length of strings in votes
  • cand := an empty map where each keys will be a list of size count, and initially they are filled with 0
  • for each v in votes, do
    • for each index i and value c in v, do
      • increase cand[c, i] by 1
    • sort cand items in descending order based on value, when values are same, sort them alphabetically
    • return a string by concatenating the sorted elements.

Let us see the following implementation to get better understanding −

Example 

Live Demo

from collections import defaultdict
class Solution:
   def solve(self, votes):
      count = len(votes[0])
      cand = defaultdict(lambda: [0] * count)
      for v in votes:
         for i, c in enumerate(v):
            cand[c][i] += 1
      return "".join(sorted(cand.keys(), key=lambda x: (cand[x], -ord(x)), reverse=True))
     
ob = Solution()
votes = ["zyx", "zxy", "xyz"]
print(ob.solve(votes))

Input

["zyx", "zxy", "xyz"]

Output

zxy
raja
Published on 02-Dec-2020 05:12:37
Advertisements