views:

89

answers:

5

level: beginner

word= 'even' 
dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} 

i want to know if word is entirely composed of letters in dict2 my approach:

step 1 : convert word to dictionary(dict1)

step2:

for k in dict1.keys(): 
        if k in dict2: 
               if dict1[k] != dict2[k]: 
                   return False 
               return True 

by adding a print statement i can see that this simply ends too early e.g. as soon as the first IF condition is met the loop exits and i won't get a correct answer. i think this is easy but google and python doc didn't return any good hints so i'm trying here.

Thanks Baba

UPDATE

the number of times that each letter ocurs in the word needs to be smaller or equal to the number of times it apears in dict2. That way i am guaranteed that word is entirely made up of elements of dict2.

for k in word.keys(): # word has ben converted to key already
    if k not in hand:
        return False
    elif k in hand:
      if word[k] > hand[k]:  
          return False
return True
+3  A: 
>>> word= 'even'
>>> dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}
>>> set(word).issubset(set(dict2.keys()))
True
MattH
To explain the above a bit... because you don't need the key->value relationship, a list or set is what you're looking for (not a dict). Since you don't need the order to matter, and explicitly want only one element of each type, a set is more appropriate. `.keys()` returns a list, so you use the set() constructor to make both the word and the key list into sets.
jkerian
A: 

in your code, just move the "return True" to be outside all the loops. That is, only return true if your loops complete without finding a non-matching value. Whether that's truly what you want for your actual code is hard to say, but moving the "return True" fixes the logic error in the code you posted.

Bryan Oakley
A: 

You only want to return true after all the checks, so stick it after the loop. Here it is as a straight modification of your code:

for k in dict1.keys(): 
    if k in dict2: 
        if dict1[k] != dict2[k]: 
            return False 
return True 
Zubin
Thanks Zubin and Brian for pointing out the proper use of return functions! That was just the refresher i needed. I have updated my post now with what i bieve is the code i needed to write.
Baba
A: 

Unless you need it for something else, don't bother constructing dict1. Just do this:

for c in word:
    if c not in dict2:
        return False
return True

Of course, you could also use a set instead of a dict to hold the letters.

Nathan Davis
A: 
>>> word = {'e':2, 'v':1, 'n':1}
>>> hand= {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}
>>> all(k in hand and v <= hand[k] for k,v in word.items())
False

and now see the true case

>>> hand['e']+=1
>>> all(k in hand and v <= hand[k] for k,v in word.items())
True
gnibbler