-1

The following function is an attempt to reverse a string. The code raise an exception

'str' object does not support item assignment error.

Code

text =''
def reverse(text):
    r=text
    m=len(text)-1
    for i in (r):
        r[m]=i
        m-=1
    return sum(r) 
ARUN ARUMUGAM
  • 43
  • 1
  • 8

1 Answers1

1

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
  • Ideally you would use "reversed" as it is more readable and probably faster (not checked). – Frogboxe Jan 28 '17 at 18:23
  • @Frogboxe reversed return a sequence not the string. so it adds more space and complecxity and more time – Sarath Sadasivan Pillai Jan 28 '17 at 18:37
  • @Frogboxe i have updated the commparison of both the approach in the answer – Sarath Sadasivan Pillai Jan 30 '17 at 01:20
  • 1
    @Frogboxe: Using `[::-1]` to get the reverse of a sequence is, like it or not, the common Python idiom. `reversed` is only superior when you need to iterate over it without copying, and even then, it's only better for reduced memory use, most of the time, the `[::-1]` slice will be faster too. – ShadowRanger Jan 30 '17 at 02:40