How to give points for each indices of list

后端 未结 2 948
旧巷少年郎
旧巷少年郎 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条回答
  •  猫巷女王i
    2021-01-26 11:54

    This does not do EXACTLY what you were asking for, it returns a tuple with two values: winner's name, and a dictionary of all parties and their values, instead of a list with only values. In my opinion, this is better for almost any case, and if you don't like it, you can convert it to a list.

    It also takes multiple parameters instead of one list too, but you can change that by simply removing the * from *args

    Notice, however, if you care about speed rather than small code, this is not the best way to do it. It does work, tho.

    It is also superior to your code in the manner of this allowing you to NOT use any of the parties names or amount of parties inside the function, which makes it possible to add, rename or remove parties.

    def voting_borda(*args):
        results = {}
        for sublist in args:
            for i in range(0, 3):
                if sublist[i] in results:
                    results[sublist[i]] += 3-i
                else:
                    results[sublist[i]] = 3-i
    
        winner = max(results, key=results.get)
        return winner, results
    
    print(voting_borda(
        ['GREEN','NDP', 'LIBERAL', 'CPC'],
        ['GREEN','CPC','LIBERAL','NDP'],
        ['LIBERAL','NDP', 'CPC', 'GREEN']
    ))
    

    Will result into: ('GREEN', {'LIBERAL': 5, 'NDP': 4, 'GREEN': 6, 'CPC': 3})

提交回复
热议问题