0
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

即使使用辅助函数,我也不确定如何缩短它,因为我们不允许创建新常量(通用变量),而只能创建局部变量

4

2 回答 2

2

尝试这个:

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-24T22:28:40.123 回答
1

您不需要所有这些字典和范围变量并定义/枚举看起来的东西。这是一个少一点的 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])

这里发生了一些神奇的蟒蛇事件。*v解包列表列表,并将它们作为单独的参数提供给zip,它返回一个迭代,它给出列表中每个参数的第一个元素,然后是列表中每个参数的第二个元素,依此类推。这具有转置矩阵的效果(交换行和列)。在这种形式中,简单地将每个列表相加将是投票总数。括在括号中的for x in语法是列表推导,这是另一个很棒的 Python 功能,可以有效地从可迭代对象创建列表。最后,index是一个列表方法这将返回具有指定值的第一个元素的索引,在这种情况下是最大值。由于 v 的元素应该具有与参与方数量相同的长度,这也将作为参与方列表的索引。

于 2012-11-24T22:54:16.400 回答