Skip to content

Instantly share code, notes, and snippets.

@phalt
Last active March 8, 2017 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phalt/e9a1e6fc591c5a675acf51e988c633ab to your computer and use it in GitHub Desktop.
Save phalt/e9a1e6fc591c5a675acf51e988c633ab to your computer and use it in GitHub Desktop.
0(n) runtime string reverse
# 0(n) runtime
# Only needs to move up to half the way of the list in order to shuffle things around.
# Something fast would be a merge sort with a key that knows the new order
words = 'hello world'
# Create to a List of the words and get the length as an Int.
# We don't actually need to cast it to a List in Python.
# Indexing Strings in Python works like a List.
lst = list(words)
length = len(lst)
for index, x in enumerate(lst):
if index >= length / 2:
# if we're at half way or more break - we've swapped everything
break
# Pull out this value
swap = lst[index]
# Move the end value to the value we just pulled out
lst[index] = lst[length - max(index + 1, 1)]
# Pop the value in swap into the end value we just moved
lst[length - max(index + 1, 1)] = swap
print lst
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment