Reason for Exception
The reason for the error is that in python string is immutable
Logic problem
The code won't work for even on a mutable list type.The code has several logical errors
Solution in detail
string is immutable in python, you can not use
r[index]= value
The above code is invalid
for reverse you may do
def reverse(text):
return text[::-1]
Optimal solution
Its worth arguing if slicing
or reversed
is better.Both are not a fair comparison as reversed
returns an iterator
Here is my comparison anyways done using ipython
In [13]: %timeit "sarath"[::-1]
The slowest run took 14.82 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 257 ns per loop
In [14]: %timeit "".join(reversed("sarath"))
The slowest run took 9.02 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.32 µs per loop