How to give points for each indices of list

后端 未结 2 971
旧巷少年郎
旧巷少年郎 2021-01-26 11:44
def voting_borda(rank_ballots):
    \'\'\'(list of list of str) -> tuple of (str, list of int)

The parameter is a list of 4-element lists that repre

2条回答
  •  不要未来只要你来
    2021-01-26 11:55

    I found your voting simulation assignment online and added a few of the constants from it here to simplify the code for solving the problem a little (although it may not look like it with their definitions at the beginning).

    The first element of the tuple returned is not exactly in the requested format -- it's a list rather than a single value -- to deal with the quite real possibility of tie votes, as illustrated with the sample data values used below for rank_ballots. Even if there wasn't a tie, the element is return is a singleton list -- which actually is usually easier to deal with than having it vary depending on there's more than one or not.

    PARTY_NAMES = ['NDP', 'GREEN', 'LIBERAL', 'CPC']
    NAME_TO_INDEX = {party:PARTY_NAMES.index(party) for party in PARTY_NAMES}
    INDEX_TO_NAME = {PARTY_NAMES.index(party):party for party in PARTY_NAMES}
    
    def voting_borda(rank_ballots):
        results = [0 for _ in PARTY_NAMES]
        MAX_POINTS = len(PARTY_NAMES)-1
        for ballot in rank_ballots:
            for i,party in enumerate(ballot):
                results[NAME_TO_INDEX[party]] += MAX_POINTS-i
    
        highest_rank = max(results)
        winners = [INDEX_TO_NAME[i] for i,total in enumerate(results) if total == highest_rank]
        return winners, results
    
    rank_ballots = [['GREEN','NDP', 'LIBERAL', 'CPC'],
                    ['GREEN','CPC','LIBERAL','NDP'],
                    ['LIBERAL', 'GREEN', 'NDP', 'CPC'],
                    ['LIBERAL','NDP', 'CPC', 'GREEN'],]
    
    print(voting_borda(rank_ballots))
    

    Output:

    (['GREEN', 'LIBERAL'], [5, 8, 8, 3])
    

提交回复
热议问题