相关疑难解决方法(0)

在Python中反转一个字符串

reversePython的str对象没有内置函数.实现此方法的最佳方法是什么?

如果提供非常简洁的答案,请详细说明其效率.例如,是否将str对象转换为其他对象等.

python string

1288
推荐指数
9
解决办法
123万
查看次数

快速和pythonic的方式来找出一个字符串是一个回文

[编辑:有人指出我使用了不正确的palindrom概念,现在我已经编辑了正确的功能.我在第一个和第三个例子中也做了一些优化,其中for语句一直到它达到字符串的一半]

我已经为一个检查字符串是否为回文的方法编写了三个不同的版本.该方法实现为类"str"的扩展

该方法还将字符串转换为小写,并删除所有准时和空格.哪一个更好(更快,pythonic)?

以下是方法:

1)这是我想到的第一个解决方案:

    def palindrom(self):
        lowerself = re.sub("[ ,.;:?!]", "", self.lower())
        n = len(lowerself)
        for i in range(n//2):
            if lowerself[i] != lowerself[n-(i+1)]:
               return False
        return True
Run Code Online (Sandbox Code Playgroud)

我认为这个更快,因为没有字符串的转换或反转,并且for语句在第一个不同的元素处断开,但我不认为这是一种优雅和pythonic的方式

2)在第二个版本中,我使用在stackoverflow上创建的解决方案进行转换(使用高级切片字符串[:: - 1])

# more compact
def pythonicPalindrom(self):
    lowerself = re.sub("[ ,.;:?!]", "", self.lower())
    lowerReversed = lowerself[::-1]
    if lowerself == lowerReversed:
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

但我认为切片和字符串之间的比较使这个解决方案变慢.

3)我想到的第三个解决方案,使用迭代器:

# with iterator
def iteratorPalindrom(self):
    lowerself = re.sub("[ ,.;:?!]", "", self.lower())
    iteratorReverse = reversed(lowerself)
    for char in lowerself[0:len(lowerself)//2]:
        if next(iteratorReverse) != char:
            return …
Run Code Online (Sandbox Code Playgroud)

python string optimization time-complexity

5
推荐指数
1
解决办法
822
查看次数

标签 统计

python ×2

string ×2

optimization ×1

time-complexity ×1