该作业由我的教授写在文档字符串中:
def evaluateBallot (voterPreferences, candidates):
"""
Using voterPreferences (a dict associating each voter with a list of
candidate names ordered from highest to lowest preference) and
candidates(a set of candidates still remaining in the election),
returns the vote distribution: a dict associating the name of each
candidate in the election to the number of votes that they received
>>> result = evaluateBallot(dict(x=['a','b','c'], y=['a','c','b'],z= ['c','a','b']),set(['b','c']))
>>> (result['b'],result['c'])
(1, 2)
"""
d ={}
for candidate in candidates:
d[candidate] = 0
for voterPreference in voterPreferences:
if candidate == voterPreference[0]:
d[candidate] += 1
return d
当我运行我编写的代码时,每次候选人是选民的首选时,字典都不会更新+1。我觉得错误在我的if语句中,但我不确定它到底是什么?
答案 0 :(得分:1)
如果数据与您在评论中描述的数据相似,那么我认为
for voterPreference in voterPreferences:
应改为
for voterPreference in voterPreferences.values():
因为你想让voterPreference成为['a','b','c']而不是'x'。
P.S。我不太明白为什么输出应该是b = 1和c = 2。如果在候选人中不存在而在voterPreferences中存在,你想如何处理?无视它?如果是这样,您需要在方法中使用更多逻辑来处理这个问题。
其他强>
根据您的意见,在计算最终结果时,似乎应忽略非候选人:
def evaluateBallot(voterPreferences, candidates):
d = {}
voterPrefCandOnly = [] # Just use list since we don't care about who voted
# Remove votes for non-candidates
for voterPref in voterPreferences.values():
filtered = filter(lambda x: x in cand, voterPref)
voterPrefCandOnly.append(filtered)
# Calculate the result for voting
for candidate in candidates:
d[candidate] = 0
for voterPref in voterPrefCandOnly:
if candidate == voterPref[0]:
d[candidate] += 1
return d
voterPref = dict(x=['a','b','c'], y=['a','c','b'], z=['c','a','b'])
cand = set(['b','c'])
result = evaluateBallot(voterPref, cand)
print (result['b'], result['c']) # (1, 2)
答案 1 :(得分:0)
我认为这项任务假定读者理所当然地进行了一种特定的径流投票。因此,老师似乎也暗示“每个人只投一票,而那个投票将发给他们评价最高的候选人candidates
”
这是一个完整的答案,您可以在完成后检查您的工作,或者您是否长时间陷入困境,或者希望检查您的假设:
def evaluateBallot(voterPreferences, candidates):
"""
. . .
"""
votes = collections.Counter() # or collections.defaultdict(lambda: 0)
for voter,prefOrdering in voterPreferences.items():
for desiredCandidate in prefOrdering: # go through each person's preference list
if desiredCandidate in candidates: # if candidate is still in the running
# then this person votes for that candidate
votes[desiredCandidate] += 1
break
# it is possible that the person casts no votes
return dict(votes)
答案 2 :(得分:0)
for candidate in candidates:
d[candidate] = 0
此循环结束后,candidate
具有candidates
中最后一位候选人的值。
for voterPreference in voterPreferences:
if candidate == voterPreference[0]:
d[candidate] += 1
在此循环中,我们使用剩余的candidate
值,并仅更新该候选人的投票。
我假设您要做的是检查voterPreference[0]
是否是有效候选人。为此,我们可以检查voterPreference[0]
in
是否为现有d
,并相应更新:
for voterPreference in voterPreferences:
if voterPreference[0] in d:
d[voterPreference[0]] += 1
我们可以通过使用voterPreference
的元组解包来简化此操作,如果我们知道它有多长项,或者将voterPreference[0]
分配给另一个变量。此外,您的3空格缩进是非标准的;请考虑切换到4:)