【问题标题】:Python Consecutive charactersPython 连续字符
【发布时间】:2020-04-21 16:43:45
【问题描述】:

如果给定一个字符串,仅当字符连续重复超过 3 次时,用该字符重复的次数替换该字符,如下所示

输入:aaaa 输出:5Za

输入:addeeeeeuyyyyy 输出:add4Zeu5Zy

尝试如下:

>>> from itertools import groupby
>>> strs="aaaaa"
>>> [[k, len(list(g))] for k, g in groupby(strs)]
[['a', 5]]
>>> 

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    与您使用的思维过程相同。

    from itertools import groupby
    
    def condense(strs):
        new_str = ''
    
        for k, g in groupby(strs):
            length = len(list(g))
            if length > 3:
                new_str += f'{length}Z{k}'
            else:
                new_str += k*length
        return new_str
    
    print(condense('aaaaa '))
    print(condense('addeeeeuyyyyy'))
    

    【讨论】:

      【解决方案2】:

      你有一个很好的部分 - 你需要实施仅缩写出现 4 次以上的连续字母的限制,并将 'Z' 添加到输出中。

      你可以这样做:

      from itertools import groupby
      
      
      def run_length_encode(data):
          result = []
          for letter,amount in ( (k, len(list(g))) for k, g in groupby(data)):
              result.append(letter*amount if amount < 4 else f'{amount}Z{letter}')
      
          return ''.join(result)
      
      data = "someaaaaabbbcdccdd"  
      print(data, run_length_encode(data), sep = "=>" ) 
      

      输出:

      someaaaaabbbcdccdd => some5Zabbbcdccdd
      

      您可以在此相关帖子中找到更多解决方案(正则表达式 f.e.):

      【讨论】:

        【解决方案3】:
        s=input()
        ini=""
        ans=""
        for i in range(len(s)):
            if ini=="":
                ini=s[i]
                c=0
            if ini==s[i]:
                c=c+1
            if ini!=s[i]:
                if c>=3:
                    ans=ans+str(c)+"Z"+ini
                else:
                    ans=ans+c*ini
                ini=s[i]
                c=1
        if c!=0 and c<3:
            ans=ans+c*ini
        elif c!=0 and c>=3:
            ans=ans+str(c)+"Z"+ini
        print(ans)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-07-30
          • 1970-01-01
          • 2018-07-08
          • 2015-04-01
          • 2019-01-12
          • 1970-01-01
          • 2020-03-20
          相关资源
          最近更新 更多