aboutsummaryrefslogtreecommitdiff
path: root/challenge-063/paulo-custodio/python/ch-1.py
diff options
context:
space:
mode:
authorMohammad Sajid Anwar <Mohammad.Anwar@yahoo.com>2024-09-18 19:59:32 +0100
committerGitHub <noreply@github.com>2024-09-18 19:59:32 +0100
commit85073f31dae3decce780d1fd66cdcb79c82c7f65 (patch)
tree318d3bc02836f4cde215f7f15e9ec875c74a1490 /challenge-063/paulo-custodio/python/ch-1.py
parentbfe139d559d498bcf1ae48cc08520bfc99ee9b85 (diff)
parent51c035e04c5ae5f9f02555206f57eb675a737617 (diff)
downloadperlweeklychallenge-club-85073f31dae3decce780d1fd66cdcb79c82c7f65.tar.gz
perlweeklychallenge-club-85073f31dae3decce780d1fd66cdcb79c82c7f65.tar.bz2
perlweeklychallenge-club-85073f31dae3decce780d1fd66cdcb79c82c7f65.zip
Merge pull request #10860 from pauloscustodio/master
Add Python solutions
Diffstat (limited to 'challenge-063/paulo-custodio/python/ch-1.py')
-rw-r--r--challenge-063/paulo-custodio/python/ch-1.py45
1 files changed, 45 insertions, 0 deletions
diff --git a/challenge-063/paulo-custodio/python/ch-1.py b/challenge-063/paulo-custodio/python/ch-1.py
new file mode 100644
index 0000000000..5fb968ca0d
--- /dev/null
+++ b/challenge-063/paulo-custodio/python/ch-1.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python3
+
+# Challenge 063
+#
+# TASK #1 > Last Word
+# Submitted by: Mohammad S Anwar
+# Reviewed by: Ryan Thompson
+#
+# Define sub last_word($string, $regexp) that returns the last word matching
+# $regexp found in the given string, or undef if the string does not contain a
+# word matching $regexp.
+#
+# For this challenge, a "word" is defined as any character sequence consisting
+# of non-whitespace characters (\S) only. That means punctuation and other
+# symbols are part of the word.
+#
+# The $regexp is a regular expression. Take care that the regexp can only match
+# individual words! See the Examples for one way this can break if you are not
+# careful.
+#
+# Examples
+# last_word(' hello world', qr/[ea]l/); # 'hello'
+# last_word("Don't match too much, Chet!", qr/ch.t/i); # 'Chet!'
+# last_word("spaces in regexp won't match", qr/in re/); # undef
+# last_word( join(' ', 1..1e6), qr/^(3.*?){3}/); # '399933'
+
+import re
+import unittest
+
+def last_word(text, pattern):
+ words = text.split(' ')
+ for word in reversed(words):
+ if re.search(pattern, word, re.IGNORECASE):
+ return word
+ return None
+
+class TestLastWord(unittest.TestCase):
+ def test_last_word(self):
+ self.assertEqual(last_word(' hello world', r'[ea]l'), 'hello')
+ self.assertEqual(last_word("Don't match too much, Chet!", r'ch.t'), 'Chet!')
+ self.assertIsNone(last_word("spaces in regexp won't match", r'in re'))
+ self.assertEqual(last_word(' '.join(str(i) for i in range(1, int(1e6) + 1)), r'^(3.*?){3}'), '399933')
+
+if __name__ == '__main__':
+ unittest.main()