在选举中给出一系列候选人的名字。数组中的候选人名称代表投票给该候选人。打印获得最多选票的候选人的姓名。如果有领带,打印一个按字典顺序较小的名字。 例如:
null
Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john"};Output : JohnWe have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The candidatesJohn and Johny get maximum votes. Since Johnis alphabetically smaller, we print it.
我们有解决这个问题的现有方案,请参考 在以候选人名字代表选票的选举中找到获胜者 链接我们可以使用python快速解决这个问题 字典数据结构 . 方法1: 方法很简单,
- 使用计数器(迭代器)方法将给定的投票列表转换为字典。我们会有一本字典,上面有候选名字 钥匙 其频率(计)为 价值 .
- 由于超过1名候选人可能会获得相同数量的选票,在这种情况下,我们需要按字典顺序打印较小的名称,因此现在我们将通过遍历之前创建的字典来创建另一个字典,投票计数将是 钥匙 候选人的名字将被删除 价值 .
- 现在找到为候选人投票的最大票数的值,并获得映射到该计数值的候选人列表。
- 对最大得票数相同的候选人列表进行排序,并打印排序列表的第一个元素,以便按字典顺序打印较小的名称。
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 ) |
输出:
john
方法2: 这是一个较短的方法。 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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END