1

作业由我的教授写在文档字符串中:

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 语句中,但我不确定它到底是什么?

4

3 回答 3

1

如果数据与您在评论中描述的一样,那么我认为

for voterPreference in voterPreferences:

应该改为

for voterPreference in voterPreferences.values():

因为您希望 voterPreference 是 ['a','b','c'] 而不是 'x'。

PS我不太明白为什么输出应该是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)
于 2012-04-20T04:12:01.623 回答
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 :)

于 2012-04-20T06:07:00.710 回答
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)
于 2012-04-20T04:13:18.223 回答