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即使使用helper函数,我也不确定如何缩短这段时间,因为我们不能创建新的常量(通用变量),只能创建局部变量
发布于 2012-11-25 06:28:40
试试这个:
for sub_list in range_votes:
for i in range(4):
PARTY_INDICES[i] += sub_list[i]
return ( {PARTY_INDICES[0] : 'NDP', PARTY_INDICES[1] : 'GREEN', ...}[max(PARTY_INDICES)],
PARTY_INDICES )这是我愿意写的最短的内容;-)
发布于 2012-11-25 06:54:16
你不需要所有那些dicts和range变量以及定义/枚举的东西。这是更少的C语言和更多的python:
votes=[[5, 4, 1, 4], [3, 2, 2, 5], [3, 3, 1, 4,]]
parties=['NDP','GREEN','LIBERAL','CPC']
def voting_range(v):
totals = [sum(x) for x in zip(*v)] # transpose row/col of list of lists
pname = parties[totals.index(max(totals))]
return (pname,totals)
>>> voting_range(votes)
('CPC',[11, 9, 4, 13])这里有一些神奇的python的东西。*v解压列表,并将它们作为单独的参数提供给zip,后者返回一个迭代器,该迭代器给出列表中每个参数的第一个元素,然后是列表中每个参数的第二个元素,依此类推。这具有转置矩阵(交换行和列)的效果。在这种形式下,简单地将每个列表相加将是投票总数。括在括号中的for x in语法是一个list comprehension,这是另一个非常棒的python特性,它可以有效地从可迭代对象创建列表。最后,index是一个list method,它将返回具有指定值的第一个元素的索引,在本例中是最大值。由于v的元素应该与参与方的数量具有相同的长度,因此这也将用作参与方列表的索引。
https://stackoverflow.com/questions/13546205
复制相似问题