Need help so that if user input "goood" it should print not from the above letters. if user input god is should be valid word
valid = ['g', 'o', 'o', 'd', 'c']
print(valid)
word = input('please make a word using above letters: ')
if any(letter in word for letter in valid):
print('yes valid word')
else:
print('not from the above letter')
CodePudding user response:
You can make a counter containing letter count then use that to compare if the count of letters in the valid list is greater than or equal to the occurences of the letter in the word
from collections import Counter
v_count = Counter(valid)
all(v_count[letter] >= word.count(letter) for letter in set(word))
CodePudding user response:
valid = ['g', 'o', 'o', 'd', 'c']
def is_valid(test_word,alphabet):
valid_copy = alphabet[:]
for letter in test_word:
try:
valid_copy.remove(letter)
except ValueError:
# there are no more of this letter in the word
print("Invalid Word")
return False
print("Valid Word")
return True
is_valid("good",valid)
is_valid("food",valid)
if you need to rapidly test many words there are likely(definitely) better ways to do this
CodePudding user response:
Another option with Counter
s is to subtract
the current word from the counter, then check in the counter if any element's count is negative (or, the opposite, check if all elements' counts are positive).
>>> from collections import Counter
>>> valid = ['g', 'o', 'o', 'd', 'c']
>>> word = "god"
>>> counter = Counter(valid)
>>> counter.subtract(word)
>>> all(count >= 0 for count in counter.values())
True
Pay attention: subtract
changes the counter in-place, so you need to recreate it if you need to perform this check with other words.
CodePudding user response:
One other option is to use following:
valid = ['g', 'o', 'o', 'd', 'c']
print(valid)
len_valid = len(valid)
word = input('please make a word using above letters: ')
def sample(valid):
if (len_valid - len(valid)) == len(word):
print('yes valid word')
else:
print('not from the above letter')
for w in word:
if w not in valid:
break
elif w in valid:
valid.remove(w)
#print(w)
if len(word) != 0:
sample(valid)