Last active
July 7, 2016 04:57
-
-
Save mpurdon/794ddf75700b6618996f6f42a3c84b55 to your computer and use it in GitHub Desktop.
Reverse a string
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
""" | |
String reversal Algorithm | |
Technically we would do 'something'[::-1] to reverse a string but | |
as an excercise I did it myself without using additional memory. | |
This is technically a lie since strings are immutable in python but | |
it gives you the idea... | |
""" | |
from __future__ import print_function, unicode_literals | |
import math | |
if __name__ == "__main__": | |
# string = u'mañana' | |
string = 'superstar' | |
print(string) | |
string_chars = list(string) | |
num_chars = len(string_chars) | |
middle_char = (num_chars - 1) / 2.0 | |
num_swaps = int(math.ceil(num_chars / 2.0)) | |
start_left = int(math.floor(middle_char)) | |
start_right = int(math.ceil(middle_char)) | |
for swap in range(0, num_swaps): | |
left = start_left - swap | |
right = start_right + swap | |
string_chars[left], string_chars[right] = string_chars[right], string_chars[left] | |
print(''.join(string_chars)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment