1901090022-MIT60001-ProblemSet3(P2)

打卡记录

作业(Problem 2: Dealing with hands):

Removing letters from a hand (you implement this!)

The player starts with a full hand of n letters. As the player spells out words, letters from the set are used up. For example, the player could start with the following hand: a, q, l, m, u, i, l The player could choose to play the word quail. This would leave the following letters in the player’s hand: l, m.

You will now write a function that takes a hand and a word as inputs, uses letters from that hand to spell the word, and returns a new hand containing only the remaining letters. Your function should not modify the input hand. For example:

1
2
3
4
5
6
7
8
9
10
>> hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
>> display_hand(hand)
a q l l m u i
>> new_hand = update_hand(hand, 'quail')
>> new_hand
{'l': 1, 'm': 1}
>> display_hand(new_hand)
l m
>> display_hand(hand)
a q l l m u i

作业心得

作业要求,实现update_hand函数,根据作业中的提示,可以通过 copy 函数来实现次函数的功能。

学习的新函数:

  • Python dict.copy 函数: 复制dict,修改新的dict不会影响原来的数据; ceil()
  • Python del 函数: 删除 dict 中对应key的项

程序代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#
# Problem #2: Update a hand by removing letters
#
def update_hand(hand, word):
"""
Does NOT assume that hand contains every letter in word at least as
many times as the letter appears in word. Letters in word that don't
appear in hand should be ignored. Letters that appear in word more times
than in hand should never result in a negative count; instead, set the
count in the returned hand to 0 (or remove the letter from the
dictionary, depending on how your code is structured).

Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.

Has no side effects: does not modify hand.

word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
new_hand = hand.copy()
word = word.lower()

for letter in word:
v = new_hand.get(letter)
if v is not None:
if v == 1:
del new_hand[letter]
else:
new_hand[letter] -= 1
return new_hand