Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active June 12, 2016 09:49
Show Gist options
  • Save vlad-bezden/858e71eb4f4b00df3f843b2daedee334 to your computer and use it in GitHub Desktop.
Save vlad-bezden/858e71eb4f4b00df3f843b2daedee334 to your computer and use it in GitHub Desktop.
Interview Cake Task on Reverse Words in-place

This is an exercise from Interview Cake web site

You're working on a secret team solving coded transmissions. Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault. The message has been mostly deciphered, but all the words are backwards! Your colleagues have handed off the last step to you.

Write a function reverse_words() that takes a string message and reverses the order of the words in-place

For example:

message = 'find you will pain only go you recordings security the into if'

reverse_words(message)

returns:

'if into the security recordings you go only pain will you find'

When writing your function, assume the message contains only letters and spaces, and all words are separated by one space.

def reverse_words(data):
chars = list(data)
chars.reverse()
space_index = end_of_word(chars, 1)
start = 0
while space_index > 0:
end = space_index - 1
while start < end:
chars[start], chars[end] = chars[end], chars[start]
start += 1
end -= 1
start = space_index + 1
space_index = end_of_word(chars, start)
return ''.join(chars)
def end_of_word(data, start_index):
try:
return data.index(' ', start_index)
except ValueError:
if len(data) > start_index:
return len(data)
return 0
if __name__ == '__main__':
message = 'find you will pain only go you recordings security the into if'
result = reverse_words(message)
print(message)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment