【发布时间】:2016-10-28 10:53:11
【问题描述】:
我正在尝试调试我编写的这个程序。我如何判断给定的 word、hand 和 word_list 是返回 True 还是 False?我尝试初始化一个变量 failure 然后修改它并打印它的值。它没有打印,所以我不知道它是否表现得像它应该的那样。任何帮助表示赞赏。
我有一个返回单词列表的函数load_words()。我知道 word 在 word_list 中(我检查过),所以只是想看看 word 是否完全由字典中的键中的字母组成hand,在这种情况下它不是,所以它应该返回 False。
另外,.keys() 和 .itrrkeys() 有什么区别,有没有更好的方法来循环 hand,也许用 letter, value in hand.iteritems ()?
word = 'axel'
hand2 = {'b':1, 'x':2, 'l':3, 'e':1}
def is_valid_word(word, hand, word_list):
"""
Returns True if word is in the word_list and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list.
word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
failure = False
if word in word_list:
print hand
print [list(i) for i in word.split('\n')][0]
for letter in [list(i) for i in word.split('\n')][0]:
print letter
if letter in hand.keys():
print letter
return True
failure = True
print failure
else:
return False
failure = False
print failure
else:
return False
failure = False
print failure
is_valid_word(word,hand2,load_words())
更新我希望在我的函数中使用这个函数,但它给出了一个关键错误,即使它本身可以正常工作。
def update_hand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
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)
"""
for letter in [list(i) for i in word.split('\n')][0]:
if letter in hand.keys():
hand[letter] = hand[letter]-1
if hand[letter] <= 0:
del hand[letter]
display_hand(hand)
return hand
【问题讨论】:
标签: python dictionary boolean