我有一个模块,它应该找到给定向量列表的平均值。 问题是返回值不一致。有时它能给我预期的输出,有时却不能。你知道吗
def find_average_record(sen_set, voting_dict):
"""
Input: a set of last names, a voting dictionary
Output: a vector containing the average components of the voting records
of the senators in the input set
"""
count = len(sen_set)
total_set = voting_dict[sen_set.pop()]
for senator in sen_set:
for vote in voting_dict[senator]:
total_set[vote] += vote
return [x/count for x in total_set]
示例:
voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]}
find_average_record({'Fox-Epstein','Ravella'}, voting_dict)
# should =>[-0.5, -0.5, 0.0]
这可能是错误的,因为你已经接受了马蒂恩的回答,但我认为这是你想要的。我将senator set参数更改为一个列表,以便返回的向量中的平均值与该列表的顺序相同(并且它们的数量相同)。你知道吗
输出:
你用每个参议员的选票计数作为总票数的索引。别那么做。改用
enumerate()
。您还需要对分配给total_set
的voting_dict
列表进行复制,以避免更改可变列表:您还可以在每一列上使用
sum()
(使用zip()
来转置行和列);这样可以避免同时更改任何投票列表:任何一个版本现在都可以正确返回平均值:
此外,包含在
voting_dict
中的列表没有改变。你知道吗相关问题 更多 >
编程相关推荐