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.
This commit is contained in:
William Carroll 2020-02-18 14:29:40 +00:00
parent acf1b8c4f0
commit ca6bd29ed8

View file

@ -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)