【问题标题】:Differect Result with Replace method in PythonPython中Replace方法的不同结果
【发布时间】:2021-10-13 05:56:33
【问题描述】:

背景: 我正在编写一个程序来查找字符串中的第一个非重复字母。

测试代码 我需要实现以下逻辑:

s = "iiiiiiitya"
if 'i' in s:
    s = s.replace('i','')
print(s)

输出: tya

这很好。 它会从字符串中删除所有出现的“i”。这就是我想要的。

问题: 但是,一旦我开始在我的实际程序中实现相同的逻辑,该函数就不能正常工作,即它只删除第一次出现的 perticulare 字母,因此我的逻辑失败。

def non_rep(s):
    for el in s:
        if el in s[1:]:
            s = s.replace(el,'')
        else:
            return el
    return "No such case is matched"
str = "adiiiityda"
ch = non_rep(str)
print(ch)

输出:

预期输出: t

为什么它会这样,我尝试了很多,但它的工作方式就像在第一个(测试)代码中一样,当我将它实现到程序中时,它的行为会有所不同。

【问题讨论】:

  • 这段代码应该做什么?它会在迭代字符串时修改字符串,从而导致意外行为。还有为什么s[1:]
  • 预期的输入和输出是什么?
  • 您不应遍历字符并在每一步对整个字符串应用转换。这是非常低效的(您为长度为 n 的字符串读取 n^2 个字符)。而是先计算字符,然后按顺序列出唯一的字符(请参阅here

标签: python methods replace logic


【解决方案1】:

您可以在 Python 中对字符串使用 count 函数,如下所示:

def non_rep(s):
    for char in s:
        if s.count(char) == 1:
            return char

【讨论】:

  • 这效率不高,因为您需要为每个字符 O(n^2) 再次读取字符串
  • 没有,不过和原代码差不多。在那里,用户试图向前扫描每个字符的字符串,并使用 O(n) 的替换函数。用户没有要求最佳解决方案 - 他要求用他的代码解决问题。
【解决方案2】:

您可以使用collections.Counter 获取计数,然后只保留唯一值:

from collections import Counter

s = "iiiiiiitya"

c = Counter(s)
''.join([i for i in c if c[i]==1])

输出:tya

【讨论】:

    【解决方案3】:

    以下使用while 来实现您的想法:

    def non_rep(s):
        while s: # while s is non-empty
            el = s[0] # get the first character
            if el in s[1:]: # if the character is found in another place
                s = s.replace(el, '') # remove all of them
            else: # if not repeated
                return s[0] # return that
        return 'No such case is matched' # this is reached when depleted
    
    print(non_rep("adiiiityda")) # t
    print(non_rep("aabbcc")) # No such case is matched
    

    通常建议不要删除for 循环中的项目。如果你把print(el, s) 放在for el in s: 之后,你会看到发生了什么。你会发现el 只是跟在original 字符串adiiiityda 之后。所以在第四次迭代中,el'i's'ty'。你的代码在'ty' 中找不到这个'i',所以它返回'i',这不是你想要的。

    【讨论】:

      【解决方案4】:

      您应该注意字符串是不可变的,因此您不能在循环中更改它,它不会按照您想要的方式运行:

      def non_rep(s):
          for el in s:
              if el in s[1:]:
                  s = s.replace(el,'')
          if len(s)>0:
              return s[0]
          return "No such case is matched"
      
      str = "adiiiityda"
      ch = non_rep(str)
      print(ch)
      

      【讨论】:

        猜你喜欢
        • 2017-04-19
        • 1970-01-01
        • 1970-01-01
        • 2021-08-25
        • 2020-08-31
        • 2021-09-08
        • 2020-11-07
        • 2021-03-18
        • 1970-01-01
        相关资源
        最近更新 更多