Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Even a monkey would get this solution X-D solution in Clear category for Monkey Typing by BootzenKatzen
# Solution 1:
def count_words(text: str, words: set) -> int:
count = 0 # establishing a count for words found
for word in words: # iterating through the words list
if word in text.lower(): # if it finds the word in the lowercase version of the text
count += 1 # add to the count
return count # after all the words have been checked, return the count
"""
so I thought my solution above wasn't working, and I thought it couldn't find the word that was attached
to a bunch of random letters for some reason (in hindsight, I don't know why I thought this)
so I looked into finding a solution in re, in case that could search for the words within words better
... it wasn't working because I forgot the .lower()
I discovered this by having it print the words it found, and saw it wasn't finding the one with capital letters
not the one that was a word in a word!
"""
# Solution 2:
import re
def count_words2(text: str, words: set) -> int:
count = 0 # Same as above - establishing our count
for word in words: # iterating through the words
if re.search(word, text.lower()): # re.search() will return a match object if there is a match
# or None if there isn't, so if it's not None (and it found the word)
count += 1 # add to the count
return count # after checking all the words, return the count
if __name__ == "__main__":
print("Example:")
print(count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert (
count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3
), "Example"
assert (
count_words("Bananas, give me bananas!!!", {"banana", "bananas"}) == 2
), "BANANAS!"
assert (
count_words(
"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
{"sum", "hamlet", "infinity", "anything"},
)
== 1
), "Weird text"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
Sept. 8, 2023
Comments: