Write a function called `match` in Python that uses a regex to find any word repeated 5 times or more. Return that word. If no word is repeated 5 times or more, return an empty string.
Write a function called `match` in Python that uses a regex to find any word repeated 5 times or more. Return that word. If no word is repeated 5 times or more, return an empty string.
To solve this problem, we can use Python's `re` module to work with regular expressions. The function `match` will search for any word that is repeated 5 times or more in a given string. Here's how you can implement it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import re from collections import Counter def match(text): # Use regex to find all words in the text words = re.findall(r'\b\w+\b', text.lower()) # Count the occurrences of each word word_counts = Counter(words) # Find the first word that is repeated 5 times or more for word, count in word_counts.items(): if count >= 5: return word # If no word is repeated 5 times or more, return an empty string return "" # Example usage: text = "This is a test. This test is only a test. Test this test to see if it works. Test test test." print(match(text)) # Output: "test" |
1 2 | text = "This is a test. This test is only a test. Test this test to see if it works. Test test test." print(match(text)) # Output: "test" |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 | import re from collections import Counter def match(text): words = re.findall(r'\b\w+\b', text.lower()) word_counts = Counter(words) for word, count in word_counts.items(): if count >= 5: return word return "" |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import re from collections import Counter def match(text): words = re.findall(r'\b\w+\b', text.lower()) word_counts = Counter(words) for word, count in word_counts.items(): if count >= 5: return word return "" answer = match('hi hi hi hi hi') expected = "hi" assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' answer = match('hi hi hi hi') expected = "" assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' answer = match('hello this is is is is is a test') expected = "is" assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
All tests passed
Testing if the previous output contains the string All tests passed
: True