aboutsummaryrefslogtreecommitdiff
path: root/challenge-255/steven-wilson/python/ch-2.py
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2024-02-05 19:23:23 +0000
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2024-02-05 19:23:23 +0000
commit5bad8a7e7366e0e8b30d580332a026266f69053e (patch)
tree52602766c6f17b82a8fbc3f06d62529e7eca8501 /challenge-255/steven-wilson/python/ch-2.py
parentba3dea3468800b07b6e59414fdde55e99607e7c5 (diff)
downloadperlweeklychallenge-club-5bad8a7e7366e0e8b30d580332a026266f69053e.tar.gz
perlweeklychallenge-club-5bad8a7e7366e0e8b30d580332a026266f69053e.tar.bz2
perlweeklychallenge-club-5bad8a7e7366e0e8b30d580332a026266f69053e.zip
- Added solutions by Eric Cheung.
- Added solutions by Laurent Rosenfeld. - Added solutions by Matthew Neleigh. - Added solutions by Mark Anderson. - Added solutions by Luca Ferrari. - Added solutions by PokGoPun. - Added solutions by Robbie Hatley. - Added solutions by Thomas Kohler. - Added solutions by W. Luis Mochan. - Added solutions by Simon Proctor. - Added solutions by Steven Wilson. - Added solutions by David Ferrone. - Added solutions by Peter Meszaros.
Diffstat (limited to 'challenge-255/steven-wilson/python/ch-2.py')
-rw-r--r--challenge-255/steven-wilson/python/ch-2.py37
1 files changed, 37 insertions, 0 deletions
diff --git a/challenge-255/steven-wilson/python/ch-2.py b/challenge-255/steven-wilson/python/ch-2.py
new file mode 100644
index 0000000000..2d5fc3ab9c
--- /dev/null
+++ b/challenge-255/steven-wilson/python/ch-2.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+
+from collections import Counter
+import string
+
+
+def most_frequent_word(paragraph, banned):
+ '''Given a paragraph and a banned word. Return the most frequent word that
+ is not banned
+ >>> most_frequent_word(
+ ... "Joe hit a ball, the hit ball flew far after it was hit.", "hit")
+ 'ball'
+ >>> most_frequent_word(
+ ... "Perl and Raku belong to the same family. "
+ ... "Perl is the most popular language in the weekly challenge.", "the")
+ 'Perl'
+ '''
+ if not paragraph or not banned:
+ raise ValueError("Both strings must be non-empty.")
+
+ paragraph_no_punctuation = paragraph.translate(
+ str.maketrans("", "", string.punctuation))
+ paragraph_counter = Counter(paragraph_no_punctuation.split())
+
+ if banned in paragraph_counter:
+ del paragraph_counter[banned]
+
+ if not paragraph_counter:
+ raise ValueError("No words found in the paragraph after removing punctuation and banned word.")
+
+ return paragraph_counter.most_common()[0][0]
+
+
+if __name__ == "__main__":
+ import doctest
+
+ doctest.testmod()