0

関数の実装に問題があります。

目的は、単語内にある場合、辞書ハンド内のキーの値を減らすことです。例えば:

word = hi
hand = {'h':2,'i':1}

-> 関数 update_hand(単語,手)

hand = {'h'1}

だから私は試しました:

def update_hand(hand, word):
    for letter in range(len(word)):
        if hand.get(word[letter],0) != 0:
            hand[word[letter]] -= 1
            if hand.get(word[letter],0) == 0:
                del hand[word[letter]]
    return hand

しかし、私がそれを呼び出すと、次のようになります:

Traceback (most recent call last):
File "/home/phillip/Desktop/ps3/ps3/ps3a.py", line 168, in <module>
print update_hand('quali', {'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1})
File "/home/phillip/Desktop/ps3/ps3/ps3a.py", line 162, in update_hand
if hand.get(word[letter],0) != 0:
AttributeError: 'str' object has no attribute 'get'

だから私はそれをテストファイルに実装しようとしました(for戦利品だけ)、すべてうまくいきました...まあ、何が間違っていたのかわかりません。

ありがとう、フィリップ

4

2 に答える 2

1

そして、質問に本当に答えるために、関数を として定義しましdef update_hand(hand, word)たが、明らかにそれを として呼び出しますupdate_hand(word, hand)。dict と str はどちらも反復可能でサイジング可能ですが、str にはgetメソッドがありません。

このような問題をデバッグするための迅速かつ簡単な方法: コードに print ステートメントを追加します。

def update_hand(hand, word):
    print "update_hand(%s, %s)" % (hand, word)
    # code here

問題を修正したら、print ステートメントを削除することを忘れないでください。

また、アンチモンが述べたように、醜いインデックス作成は必要ありません。Jakob は を使用して適切なバージョンを投稿しましたcollections.Counterが、古い (< 2.7.x) Python バージョンに行き詰まっている場合は、より標準的な実装を次に示します。

def update_hand(hand, word):
    for letter in word:
        count = hand.get(letter, 0)
        if count > 1:
            # avoids a KeyError if letter was not in hand 
            # XXX spec : should this happen ?
            hand[letter] = count - 1
        else:
            # count is already <= 1 so decreasing it would make it <= 0
            del hand[letter]

    return hand
于 2012-07-04T15:56:57.417 に答える
1
from collections import Counter

hand = Counter()

def update_hand(word, hand):
    for token in word:
        if hand[token] == 0:
           del hand[token]
        else: 
           hand[token] -= 1

collections.Counterを使用すると、このタスクが簡単になります

于 2012-07-04T14:56:37.600 に答える