Reversing a String

def reverse(s):
  s = [x for x in s]
  l = len(s)
  for i in range(l // 2):
      s[i], s[l-i-1] = s[l-i-1], s[i]
  return ''.join(s)

#Challenge

SourceLanguageRuntime
DailyBytepython\(\mathcal{O}(n)\)

#Solution

for every pair of characters leading to the middle of the string, swap them.

#Proof

Loop Invariant: at the end of each iteration of the loop, the character at index \(i\) and the character at index \(l-i-1\) is at its correct position in the reversed string.

Let \(m\) be the middle of the string. This is equal to \(floor(len(s)/2)\).

Note
in the case where the string is odd, the mth character isn't moved because it's position is the same in the reversed string as it was in the original.

#Alternative Implementation

Python itself has a simple clean way to reverse collections. Here's the language specific solution.

def reverse(s):
    return s[::-1]