CONSTANTS:
NDP_INDEX = 0
GREEN_INDEX = 1
LIBERAL_INDEX = 2
CPC_INDEX = 3
各方数据出现在 4 元素列表中的索引分布。
PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX]
一个字典,其中每个键是一方名称,每个值是该方的索引。
NAME_TO_INDEX = {'NDP': NDP_INDEX,
'GREEN': GREEN_INDEX,'LIBERAL': LIBERAL_INDEX,'CPC': CPC_INDEX}
一个字典,其中每个键是一方的索引,每个值是该方的名称。
INDEX_TO_NAME = {NDP_INDEX: 'NDP',GREEN_INDEX: 'GREEN', LIBERAL_INDEX:
'LIBERAL',CPC_INDEX: 'CPC'}
def voting_range(range_votes):
'''
(list of list of int) -> tuple of (str, list of int)
#range_votes is a list of integers of range ballots for a single
#riding; the order of the inner list elements corresponds to the order
#of the parties in PARTY_INDICES.Based on range_votes, return a tuple
#where the first element is the name of the party winning the seat and
#the second is a list with the total range_votes for each party in the
#order specified in PARTY_INDICES.
>>> voting_range([[5, 4, 1, 4], [3, 2, 2, 5], [3, 3, 1, 4,]])
('CPC', [11, 9, 4, 13])
'''
NDP_count = 0
GREEN_count = 0
LIBERAL_count = 0
for sub_list in range_votes:
NDP_count += sub_list[0]
GREEN_count += sub_list[1]
LIBERAL_count += sub_list[2]
CPC_count += sub_list[3]
PARTY_INDICES[0] = NDP_count
PARTY_INDICES[1] = GREEN_count
PARTY_INDICES[2] = LIBERAL_count
PARTY_INDICES[3] = CPC_count
winner = max(NDP_count, GREEN_count, LIBERAL_count, CPC_count)
if winner == NDP_count:
return 'NDP', PARTY_INDICES
elif winner == GREEN_count:
return 'GREEN', PARTY_INDICES
elif winner == LIBERAL_count:
return 'LIBERAL', PARTY_INDICES
elif winner == CPC_count:
return 'CPC', PARTY_INDICES
即使使用辅助函数,我也不确定如何缩短它,因为我们不允许创建新常量(通用变量),而只能创建局部变量