From 20ccf25c6944641c7db4b60fa15d520686cb7036 Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Fri, 9 Feb 2024 15:28:55 +0100 Subject: feat(challenge-255/lubos-kolouch/perl,python,raku/): Challenge 255 LK Perl Python Raku --- challenge-255/lubos-kolouch/python/ch-2.py | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 challenge-255/lubos-kolouch/python/ch-2.py (limited to 'challenge-255/lubos-kolouch/python/ch-2.py') diff --git a/challenge-255/lubos-kolouch/python/ch-2.py b/challenge-255/lubos-kolouch/python/ch-2.py new file mode 100644 index 0000000000..2c2f1d6807 --- /dev/null +++ b/challenge-255/lubos-kolouch/python/ch-2.py @@ -0,0 +1,35 @@ +def most_frequent_word(p: str, w: str) -> str: + """ + Find the most frequent word in a paragraph excluding a specific word. + + :param p: Paragraph as a string. + :param w: Banned word. + :return: Most frequent word. + """ + import re + from collections import Counter + + # Clean and split the paragraph into words + words = re.findall(r"\w+", p.lower()) + + # Count the frequency of each word, excluding the banned word + word_count = Counter(words) + if w in word_count: + del word_count[w] + + # Find the most frequent word + most_frequent = word_count.most_common(1)[0][0] + + return most_frequent + + +# Test cases +print( + most_frequent_word("Joe hit a ball, the hit ball flew far after it was hit.", "hit") +) +print( + most_frequent_word( + "Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.", + "the", + ) +) -- cgit