📜  Python中的字典和计数器找到选举的获胜者

📅  最后修改于: 2022-05-13 01:55:08.192000             🧑  作者: Mango

Python中的字典和计数器找到选举的获胜者

给定选举中的候选人姓名数组。数组中的候选人姓名代表对该候选人的投票。打印获得最大票数的候选人姓名。如果有平局,则打印一个按字典顺序较小的名称。
例子:

Input :  votes[] = {"john", "johnny", "jackie", 
                    "johnny", "john", "jackie", 
                    "jamie", "jamie", "john",
                    "johnny", "jamie", "johnny", 
                    "john"};
Output : John
We have four Candidates with name as 'John', 
'Johnny', 'jamie', 'jackie'. The candidates
John and Johny get maximum votes. Since John
is alphabetically smaller, we print it.

我们有针对此问题的现有解决方案,请参阅“查找选举获胜者”,其中选票表示为候选人姓名链接。我们可以在Python中使用 Dictionary 数据结构快速解决这个问题。
方法一:
方法很简单,

  1. 使用 Counter(iterator) 方法将给定的投票列表转换为字典。我们将有一个字典,其中候选名称为Key ,其频率(计数)为Value
  2. 由于可能有超过 1 个候选人获得相同数量的选票,在这种情况下,我们需要按字典顺序打印更小的名称,因此现在我们将通过遍历先前创建的字典创建另一个字典,投票数将为Key ,候选人名称将为Value
  3. 现在找到为候选人投票的最大投票值,并获取映射到该计数值的候选人列表。
  4. 对具有相同最大票数的候选人列表进行排序,并打印排序列表的第一个元素,以便按字典顺序打印更小的名称。

Python3
# Function to find winner of an election where votes
# are represented as candidate names
from collections import Counter
 
def winner(input):
 
    # convert list of candidates into dictionary
    # output will be likes candidates = {'A':2, 'B':4}
    votes = Counter(input)
     
    # create another dictionary and it's key will
    # be count of votes values will be name of
    # candidates
    dict = {}
 
    for value in votes.values():
 
        # initialize empty list to each key to
        # insert candidate names having same
        # number of votes
        dict[value] = []
 
    for (key,value) in votes.items():
        dict[value].append(key)
 
    # sort keys in descending order to get maximum
    # value of votes
    maxVote = sorted(dict.keys(),reverse=True)[0]
 
    # check if more than 1 candidates have same
    # number of votes. If yes, then sort the list
    # first and print first element
    if len(dict[maxVote])>1:
        print (sorted(dict[maxVote])[0])
    else:
        print (dict[maxVote][0])
 
# Driver program
if __name__ == "__main__":
    input =['john','johnny','jackie','johnny',
            'john','jackie','jamie','jamie',
            'john','johnny','jamie','johnny',
            'john']
    winner(input)


Python3
from collections import Counter
 
votes =['john','johnny','jackie','johnny','john','jackie',
    'jamie','jamie','john','johnny','jamie','johnny','john']
 
#Count the votes for persons and stores in the dictionary
vote_count=Counter(votes)
 
#Find the maximum number of votes
max_votes=max(vote_count.values())
 
#Search for people having maximum votes and store in a list
lst=[i for i in vote_count.keys() if vote_count[i]==max_votes]
 
#Sort the list and print lexicographical smallest name
print(sorted(lst)[0])


输出:

john

方法二:
这是一种较短的方法。
1.统计每个人的投票数,并存储在字典中。
2. 找出最大票数。
3. 找到票数等于最大票数的相应人。
4. 由于我们要按字典顺序输出,所以对列表进行排序并打印第一个元素。

Python3

from collections import Counter
 
votes =['john','johnny','jackie','johnny','john','jackie',
    'jamie','jamie','john','johnny','jamie','johnny','john']
 
#Count the votes for persons and stores in the dictionary
vote_count=Counter(votes)
 
#Find the maximum number of votes
max_votes=max(vote_count.values())
 
#Search for people having maximum votes and store in a list
lst=[i for i in vote_count.keys() if vote_count[i]==max_votes]
 
#Sort the list and print lexicographical smallest name
print(sorted(lst)[0])

输出:

john