From ca6bd29ed8eaca616a1bc8ffceb68f00544eab36 Mon Sep 17 00:00:00 2001 From: William Carroll Date: Tue, 18 Feb 2020 14:29:40 +0000 Subject: [PATCH] Solve bonus part of reverse-words InterviewCake asks "How would you handle punctuation?". Without precise specs about what that entails, I'm supporting sentences ending with punctuation. --- scratch/deepmind/part_two/reverse-words.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/scratch/deepmind/part_two/reverse-words.py b/scratch/deepmind/part_two/reverse-words.py index d433ac594..033d11244 100644 --- a/scratch/deepmind/part_two/reverse-words.py +++ b/scratch/deepmind/part_two/reverse-words.py @@ -10,6 +10,9 @@ def reverse(xs, i, j): def reverse_words(xs): + punctuation = None + if len(xs) > 0 and xs[-1] in ".?!": + punctuation = xs.pop() reverse(xs, 0, len(xs) - 1) i = 0 j = i @@ -19,6 +22,8 @@ def reverse_words(xs): reverse(xs, i, j - 1) j += 1 i = j + if punctuation: + xs.append(punctuation) # Tests @@ -59,5 +64,11 @@ class Test(unittest.TestCase): expected = list('') self.assertEqual(message, expected) + def test_bonus_support_punctuation(self): + message = list('yummy is cake bundt chocolate this!') + reverse_words(message) + expected = list('this chocolate bundt cake is yummy!') + self.assertEqual(message, expected) + unittest.main(verbosity=2)