0

i am doing a python project and i wanna compare a string to a list of keys and values - if all the keys were to match up a certain number of times with a word string, it should return True for example - def compareTo(word, hand):

   kal = False 
   for d in wordlists: 
       if d in word: 
          kal = True 
   return kal

it always returns false how can i make it return true?!? please help!!!

so if

word = "hammer"

and

hand =  {'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1}

values represent the frequency of each letter if I insert parameters which are true, how can I make it return true and not false...

comapreTo("hammer",{'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1})

should return True and not False and comapreTo("hammers",{'a': 1, 'h': 1, 'r': 1, 'd': 2, 'e': 1}) should return false and not true!

2 Answers 2

1

You can simply use Counter to count letter frequencies:

from collections import Counter

def compareTo(word, hand):
    return Counter(word) == hand

For example, Counter("hammer") is Counter({'m': 2, 'a': 1, 'h': 1, 'r': 1, 'e': 1}); since Counter is dictionary-like, this will compare equal to {'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1}.

Counter is built in to Python 2.7 and Python 3.x. If you need to use it in Python 2.6 or earlier, you can get it from here: http://code.activestate.com/recipes/576611/.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. I would add info that Counter is in Python since 2.7. In some cases this might be a deal breaker ...
0

This should work:

def compareTo(word, hand):
    d = hand.copy()
    for c in word:
        d[c] = d.get(c, 0) - 1
        if d[c] < 0:
            return False
    return True

word = "hammer"
hand =  {'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1}

print compareTo(word, hand)  # => True    
print compareTo("hammers", hand)  # => False
print compareTo("plum", {'f': 1, 'h': 1, 'k': 1, 'm': 1, 'l': 1, 'p': 1, 'u': 1, 'y': 1})  # => True

9 Comments

how come it doesn't work for this case - >>> plum = "plum" >>> pluma = {'f': 1, 'h': 1, 'k': 1, 'm': 1, 'l': 1, 'p': 1, 'u': 1, 'y': 1} >>> print compareTo(plum, pluma) False
in what case it doesn't work? I'm getting outputs that are in comments ... If you want to make it work if hand is superset of minimum matching one than last return should be just return True
@user2152315 to make it work for your case you need to apply change from comment above
in the case "plum" and {'f': 1, 'h': 1, 'k': 1, 'm': 1, 'l': 1, 'p': 1, 'u': 1, 'y': 1} it returns False when it should return True
@user2152315 I would recommend changing problem description to strengthen that numbers in those hand dict are lower bounds - not equal values
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.