Reputation: 123
I am making a guessing word game. So if I was given word lime-tree
. Then I want to check for the possible words within that word. If I guessed lime
, tree
, time
, reel
or guess even not a real word etc. then they are all true
, since they are made from this word. How do I check if the word guessed is within this word?
I forgot to mention that the letters cannot be more than specified in the given word.
Upvotes: 1
Views: 1464
Reputation: 19733
Here is the simple one
I have use count
, if in new_word count is more for a letter it will return wrong . or at last return Correct.
>>> def word_check(original,new_word):
... for x in new_word:
... if new_word.count(x) > original.count(x):
... return "Wrong"
... return "Correct"
...
>>> word_check('lime-tree','trel')
'Correct'
>>> word_check('lime-tree','treeel')
'Correct'
>>> word_check('lime-tree','treeeel')
'Wrong'
>>> word_check('lime-tree','mile')
'Correct'
>>> word_check('lime-tree','miilet')
'Wrong'
Upvotes: 1
Reputation: 20543
You may make use of Counter
, to count all letters in given word, and subtract the letters from the word to be checked, something like this:
from collections import Counter
def check_in_given_word(given_word, to_check):
given_word_counter = Counter(given_word)
word_counter = Counter(to_check)
given_word_counter.subtract(word_counter)
#if any -ve letter count is found, it is not in given_word
if any([c < 0 for c in given_word_counter.values()]):
# do whatever you want, or return False
print "{} is NOT in {}".format(to_check, given_word)
else:
print "{} is in {}".format(to_check, given_word)
# print the counter for your info
print given_word_counter
Sample usage:
check_in_given_word('lime-tree', 'tree')
tree is in lime-tree
Counter({'e': 1, 'i': 1, 'm': 1, '-': 1, 'l': 1, 'r': 0, 't': 0})
check_in_given_word('lime-tree', 'reel')
reel is in lime-tree
Counter({'e': 1, 'i': 1, 'm': 1, '-': 1, 't': 1, 'l': 0, 'r': 0})
check_in_given_word('lime-tree', 'hello')
hello is NOT in lime-tree
Counter({'e': 2, 'i': 1, 'm': 1, '-': 1, 'r': 1, 't': 1, 'l': -1, 'o': -1, 'h': -1})
check_in_given_word('lime-tree', 'reeeeel')
reeeeel is NOT in lime-tree
Counter({'i': 1, 'm': 1, '-': 1, 't': 1, 'l': 0, 'r': 0, 'e': -2})
As you can see, all letters should be +ve values. If any negative values is found, the word to check is not in your given word.
Upvotes: 0