【问题标题】:TimeLimitError when removing all occurrences of a string from another string从另一个字符串中删除所有出现的字符串时的 TimeLimitError
【发布时间】:2021-01-28 23:37:50
【问题描述】:

我正在做一个练习,我必须从另一个字符串中删除所有出现的字符串,虽然它有效,但似乎程序正在迭代并且无限次,我无法修复它。我知道有一个 string.replace() 函数,但我想尝试在不使用该函数的情况下解决问题。 这是代码:

''' def remove_all(substr,theStr):

index = theStr.find(substr)
if index > 0:
    newstr = ""
    while index > 0:
        sizsub = len(substr)
        newstr = theStr[:index] + theStr[(index + len(substr)):]
        index = newstr.find(substr)
    return newstr
else:
    return theStr

remove_all("an", "banana")

'''

错误消息:“TimeLimitError:程序超出运行时间限制。在第 9 行”

提前致谢。

【问题讨论】:

    标签: python string while-loop


    【解决方案1】:

    首先,您应该检查索引是否大于 -1,而不是 0,因为 0 是第一个索引。 在while 内部,您每次都在剪切初始的theStr,这导致newstr 是同一件事并陷入循环。

    您可以通过为newstr 赋予等于theStr 的初始值并剪切newstr 而不是theStr 内部循环来解决此问题。

    def x(substr, theStr):
        index = theStr.find(substr)
        if index > -1:
            newstr = theStr
            while index> -1: 
                sizsub = len(substr)
                newstr = newstr[:index] + newstr[index + sizsub:]
                index = newstr.find(substr)
            return newstr
        else:
            return theStr
    
    print(x('an', 'banana'))
    # prints => ba
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 2014-08-07
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 2011-12-19
      相关资源
      最近更新 更多