I'm trying to debug this program I wrote. How can I tell if, for a given word, hand, and word_list, it returns True or False? I tried initializing a variable failure and then modifying it and printing it's value. It isn't printing, so I don't know if it is behaving like it's supposed to. Any help is appreciated.
I have a function load_words() that returns a list of words. I know word is in word_list (I checked), so just trying to see if word is composed entirely of letters from the keys in the dictionary hand, which in this case it isn't, so it should return False.
Also, what is the difference between .keys() and .iterrkeys(), and is there a better way of looping through hand, perhaps with 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())
UPDATE I wish to use this function in my function, but it gives a key error, even though it works fine on its own.
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