Home > database >  How do I check if a string only has letters from a list of letters in Python
How do I check if a string only has letters from a list of letters in Python

Time:09-28

word represents the string I am checking, letters is a list of random letters. I need to make sure that the word only contains letters in a list. However if their are repeating letters, there needs to be that many repeating letters in the list. If returned True it needs to remove the letters used in the word from the list. I am really struggling with this one.

example: w.wordcheck('feed') -> False
letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
w.wordcheck('gag') -> false

w.wordcheck('gene')  -> True

w.wordcheck('gene') -> True
print(letters) -> ['f', 'a', 'z']



letters = []
def wordcheck(self, word)
    for char in word:
        if char not in self.letters:
            return False
        else:
            return True

CodePudding user response:

One way using collections.Counter:

from collections import Counter

letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
cnt = Counter(letters)

def wordcheck(word):
    return all(cnt[k] - v >= 0 for k, v in Counter(word).items())

Output:

wordcheck("gag")
# False

wordcheck("gene")
# True

CodePudding user response:

You can do solve , this problem by finding the case where word result into false. these cases are, when the character is not in the letters and character frequency in word is more than the character frequency in the letter.

once if any of condition meet, return false else return true.

# your code goes here
from collections import Counter

letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
letters_count = Counter(letters)


def func(word):
    word_count = Counter(word)
    check = True
    for word in word_count:
        if word not in letters_count or word_count.get(word)>letters_count.get(word):
            check = False
            break
    return check

l = ['feed', 'gag', 'gene']
for i in l:
    print(func(i))

output

False
False
True

CodePudding user response:

There are already better answers, but I felt like adding a novel solution just for the heck of it:

from itertools import groupby


def chunks(s):
    return set("".join(g) for _, g in groupby(sorted(s)))


def wordcheck(word, valid_letters):
    return chunks(word) <= chunks(valid_letters)

Steps:

  1. Turn word into a set of chunks, e.g.: "gag" -> {"a", "gg"}
  2. Turn valid_letters into a set of chunks
  3. Check if word is a subset of valid_letters

Limitations:

  1. This is a mostly silly implementation
  2. This will only return True if the exact number of repeated letters is present in valid_letters, e.g.: if valid_letters = "ccc" and word = "cc" this will return False because there are too few c's in word
  3. It's really inefficient
  • Related