0

我有一个键列表:带有附加到特定键的整数值的值...

这些整数值表示特定手牌中的字母数...

例如,这是一只手-

hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} 
displayHand(hand) # Implemented for you
a q l l m u i
hand = updateHand(hand, 'quail') # You implement this function!
hand
{'l': 1, 'm': 1}
displayHand(hand)
l m  

在这种情况下 - 这个电话 -

updateHand({'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1}, quail)

应该导致这个输出 -

{'a': 0, 'q': 0, 'u': 0, 'i': 0, 'm': 1, 'l': 1}

注意到鹌鹑一词中的字母是如何全部减一的吗?

那么如果键的值大于零,如何通过减一来更改键的值?

这是我到目前为止的代码 -

for c in word:

    if c in hand:
        x = int(hand.get(c))
        x -= 1

return hand
4

2 回答 2

1

这是你的代码:

def updateHand(hand, word):
    for c in word:
        if c in hand:
            x = int(hand.get(c))
            x -= 1
    return hand

但这对hand. 为什么不?好吧,试图改变东西的那条线就是这x -= 1条线。但这只会改变 的值x,您刚刚将其定义为int(hand.get(c))。在 Python 中,这意味着如果hand值为2for c,您将设置x = 2. 但这并不意味着改变x会改变cin的值hand。相反,您需要做一些不同的事情:

def updateHand(hand, word):
    for c in word:
        if c in hand:
            hand[c] -= 1
    return hand

在这种特殊情况下无关紧要,但这个函数实际上修改了输入hand,然后返回相同的。例如:

>>> hand = {'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1}
>>> new_hand = updateHand(hand, 'quail')
>>> new_hand
{'l': 1, 'm': 1}
>>> hand
{'l': 1, 'm': 1}

通常,您要么希望updateHand返回一个新字典而让旧字典不理会,要么让它不返回任何内容而只修改输入参数。因为看起来你已经获得了代码

hand = updateHand(hand, 'quail')

你应该做这两个中的第一个。实现此目的的一种方法是添加hand = hand.copy()updateHand; 然后它会留下旧的。


现在,另一件事是,如果它们曾经是 1,那么您的代码会将0值放入输出中,但您的分配根本不包括它们。我会让你弄清楚如何准确地处理这种情况,但作为一种方法的提示:你可以通过语句从字典中删除项目del hand[c]


不建议您这样做,但作为@Jared 展示一下 Python 的旁白::)

def updateHand(hand, word):
    return collections.Counter(hand) - collections.Counter(word)

(在调用中包装返回值dict以使其完全成为所需的接口)

于 2013-03-09T01:08:50.203 回答
0

嗯...在我们了解该语言之前,我遇到了麻烦,所以我不妨发布它,但它是 Javascript。不知道其中有多少可能是 Pythonizable ©,但它给出了我评论的要点,并且有一个工作小提琴可供查看。

请注意,使用带有打开的 Javascript 控制台的浏览器来查看输出。

var hand = {a:1, q:1, l:2, m:1, u:1, i:1},
    quail = 'quail';

displayHand(hand);

hand = updateHand(hand, quail);

displayHand(hand);

function displayHand(obj) {
    var log = '',
        key;

    for (key in obj) {
        if (obj.hasOwnProperty(key) && obj[key]) {
            log += key;
        }
    }

    console.log(log.split('').join(' ') || 'Nothing');
}

function updateHand(obj, tokens) {
    var pos = 0,
        token;

    while (token = tokens[pos++]) {
        if (obj.hasOwnProperty(token) && obj[token] > 0) {
            obj[token]--;
        }
    }

    return obj;
}

http://jsfiddle.net/userdude/ybrn4/

于 2013-03-09T01:09:17.377 回答