1

割り当ては、私の教授によって docstring に書き込まれます。

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]それind応じて更新します。

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

この割り当ては、読者が特定の種類の決選投票を当然のことと考えていることを前提としていると思います。したがって、教師は、「各人が正確に 1 票を投じ、その票が最も評価の高い候補者に送られる」ことをほのめかしているようにも思われます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 に答える