Number of words in text you can fully type using this keyboard

Question:

There is such a task with Leetcode. Everything works for me when I press RUN, but when I submit, it gives an error:

text = "a b c d e"

brokenLetters = "abcde"

Output : 1

Expected: 0

def canBeTypedWords(self, text, brokenLetters):
for i in brokenLetters:
    cnt = 0
    text = text.split()
    s1 = text[0]
    s2 = text[1]

    if i in s1 and i in s2:
        return 0
    else:
        cnt += 1
        return cnt

Can you please assist what I missed here?

Everything work exclude separate letters condition in a text.

Asked By: user531309

||

Answers:

So consider logically what you have to do, then write that algorithmically.

Logically, you have a list of words, a list of broken letters, and you need to return the count of words that have none of those broken letters in them.

"None of those broken letters in them" is the important bit — if even one broken letter is in the word, it’s no good.

def count_words(broken_letters, word_list) -> int:
    words = word_list.split()  # split on spaces
    broken_letters = set(broken_letters)  # we'll be doing membership checks
                                          # on this kind of a lot, so changing
                                          # it to a set is more performant
    count = 0
    for word in words:
        for letter in word:
            if letter in broken_letters:
                # this word doesn't work, so break out of the
                # "for letter in word" loop
                break
        else:
            # a for..else block is only entered if execution
            # falls off the bottom naturally, so in this case
            # the word works!
            count += 1

    return count

This can, of course, be written much more concisely and (one might argue) idiomatically, but it is less obvious to a novice how this code works. As exercise to the reader: see if you can understand how this code works and how you might modify it if the exercise was, instead, giving you all the letters that work rather than the letters that are broken.

def count_words(broken_letters, word_list) -> int:
    words = word_list.split()
    broken_letters = set(broken_letters)
    return sum((1 for word in words if all(lett not in broken_letters for lett in word)))
Answered By: Adam Smith
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.