反向函数是否只使用一个参数(一个字符串)?

时间:2017-01-28 17:34:28

标签: python algorithm python-3.x

以下函数是尝试反转字符串。 代码引发异常

'str' object does not support item assignment错误。

代码

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

1 个答案:

答案 0 :(得分:1)

例外原因 出错的原因是python字符串是不可变的

逻辑问题 即使在可变列表类型上,代码也不会起作用。代码有几个逻辑错误

详细解决方案

string在python中是不可变的,你不能使用

   r[index]= value 

以上代码无效

反向你可以做

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

最佳解决方案

如果slicingreversed更好,那么值得争论。因为reversed返回迭代器

,所以这两者都不公平比较

以下是使用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