Python字符串倒序-7. Reverse Integer

今天做了下LeetCode上面字符串倒序的题目,突然想Python中字符串倒序都有哪些方法,于是网上查了下,居然有这么多种方法:

个人觉得,第二种方法是最容易想到的,因为List中的reverse方法比较常用,做LeetCode题目7. Reverse Integer也用了这种方法,程序耗时65ms

#字符串的反转

#用到for循环的步长参数,从大到小循环,到0为止
def reverse1 (s):
    rt = ''
    for i in range(len(s)-1, -1, -1):
        rt += s[i]
    return rt
#用到list的反转函数reverse()
def reverse2 (s):
    li = list(s)
    li.reverse()
    rt = "".join(li)
    return rt
#用到切片的步长参数,负数代表从右往左遍历
def reverse3 (s):
    return s[::-1]
#用到python内建函数reversed(str)
def reverse4 (s):
    return "".join(reversed(s))
#用到python内建函数reduce()

"""

def reduce(function, sequence, initial=None):
  reduce(function, sequence[, initial]) -> value

  Apply a function of two arguments cumulatively to the items of a sequence,
  from left to right, so as to reduce the sequence to a single value.
  For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
  ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
  of the sequence in the calculation, and serves as a default when the
  sequence is empty.

"""

#简单的说就是遍历序列s,放入第一个参数的函数中执行,执行之后结果作为函数的第一个参数,序列的下一个元素作为第二个参数,再次运算

#比如第一次,x='1',y='2';第二次:x='21',y='3';第三次:x='321',y='4'...
from functools import reduce
def reverse5 (s):
    return reduce(lambda x,y:y+x,s)

好奇的是,到底哪个方法运算速度更快呢,于是实验了一下:

显然,第三个方法速度最快,也就是利用切片的步长参数。

可见,这个方法比reverse方法更快更方便,且适用于没有reverse方法的字符串和元组。

于是用该方法替换LeetCode第7题的答案:59ms,果然快了一丢丢:)

附LeetCode 7. Reverse Integer代码:

增加了负数和超过int范围的判断,满足leetcode第7题需要:

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        y = str(x)
        flag = 0
        if '-' == y[0]:
            flag = 1
            y = y[1:]
            result='-'
        else:result = ''
        result += y[::-1]
        if int(result) > 2**31-1 or int(result) < 1-2**31 :return 0
        return int(result) 
原文地址:https://www.cnblogs.com/yuanzhaoyi/p/5976920.html