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
Source | Language | Runtime |
---|---|---|
DailyByte | python |
#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
Let
- In the first iteration
. The first character ( ) is moved to the end of the string and the last character ( ) is moved to the start of the string. Maintaining the loop invariant. - In the
iteration, for any less than , the value is characters from the middle of the string and characters from its position in the reversed string. . Thus the value is moved to the st position and the st value is moved to the position. Maintaining the loop invariant. - At the end of the loop there's a case split depending on if the string length is
odd or even.
- If the string is odd then
. The st and the th characters are swapped. Loop invariant holds and the loop terminates. - If the string is even then
and this character is swapped with st character which is the character next to (I.E ). The last pair of characters is swapped. The loop invariant holds and the loop terminates.
- If the string is odd then
Note
in the case where the string is odd, the
m
th 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]