Created
May 24, 2013 09:57
-
-
Save bootandy/5642514 to your computer and use it in GitHub Desktop.
python coding for interviews question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Returns the sentence with the order of the words reversed, | |
Coding for Interviews contains too many gifs. -> | |
gifs. many too contains Interviews for Coding | |
""" | |
def reverse_space_n(s): | |
rev = s.split(' ') | |
print ' '.join(rev[::-1]) | |
def reverse_space_one(s): | |
outer_i = 0 | |
outer_j = len(s) | |
while(outer_i < outer_j): | |
# Find the spaces | |
for i in range(outer_i, len(s)): | |
if s[i] == ' ': | |
break | |
for j in range(outer_j, 0, -1): | |
if s[j-1] == ' ': | |
break | |
# If i and j have found the same word (happens on odd number of words) then stop | |
if i > j: | |
break; | |
# Swap the words round while maintaining the order of the rest of 's' | |
s = s[0:outer_i] + s[j:outer_j] + s[i:j] + s[outer_i:i] + s[outer_j:] | |
# Move the outer markers in by one word. | |
outer_i, outer_j = outer_i + (outer_j - j), outer_j - (i - outer_i) | |
outer_i += 1 | |
outer_j -= 1 | |
print s | |
reverse_space_n('Coding for Interviews contains too many gifs.') | |
reverse_space_one('Coding for Interviews contains too many gifs.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment