【问题标题】:How to escape parentheses python如何转义括号python
【发布时间】:2020-07-18 12:12:05
【问题描述】:

我是编程新手。本练习的目标是将字符串转换为新字符串,其中如果该字符在原始字符串中仅出现一次,则新字符串中的每个字符为“(”,如果该字符在原始字符串中多次出现,则为“)”细绳。在确定字符是否重复时忽略大小写。

但是当代码遇到 ) -- 右括号会产生错误的输出。我发现问题出在正则表达式上,但我不知道如何修复代码。

from collections import Counter

def duplicate_encode(word):
    counter = Counter(word.lower())
    counter2 = dict.copy(counter)

    print(counter2)

    for k,v in counter2.items():
        if counter2[k]==1:
            counter2[k]='('
        else:
            counter2[k]=')'
  
    for key in counter2.keys():
        word = str(word.lower()).replace(key, str(counter2[key])) 
    
    return word

例如:

duplicate_encode('yy! R)!QvdG') 应该返回 )))((()(((( 但我得到了(((((((((((。

【问题讨论】:

    标签: python parentheses


    【解决方案1】:
    from collections import Counter
    
    
    def duplicate_encode(word):
        res = list(word.lower())
        counter = Counter(word.lower())
        counter2 = dict.copy(counter)
    
        print(counter2)
    
        for k, value in enumerate(res):
            if counter2[value] == 1:
                res[k] = '('
            else:
                res[k] = ')'
    
        # for key in counter2.keys():
        #     word = str(word.lower()).replace(key, str(counter2[key]))
    
        return "".join(res)
    
    
    res = duplicate_encode('yy! R)!QvdG')
    print("res", res)
    

    【讨论】:

      【解决方案2】:

      当您的输入字符串包含大括号时会出现问题,例如( 或)。
      发生这种情况时,就像在您的示例中那样,错误的字符会被替换,您可以通过在代码中添加 print() 语句来验证,每次更改 word 时。
      我已经替换了你代码中的那部分。

      from collections import Counter
      
      def duplicate_encode(word):
          counter = Counter(word.lower())
          counter2 = dict.copy(counter)
      
          print(counter2)
      
          for k,v in counter2.items():
              if counter2[k]==1:
                  counter2[k]='('
              else:
                  counter2[k]=')'
          
          print(counter2)
          
          new_word = ''
          for character in word:
              new_word += counter2[character.lower()]
          
          return new_word
      

      但是请注意,代码有很多冗余和不必要的内存使用。可以简化为:

      from collections import Counter
      
      def duplicate_encode(word):
          lower_word = word.lower()
          new_word = ''
          counter = Counter(lower_word)
          
          for char in lower_word:
              if counter[char] > 1:
                  new_word += ')'
              else:
                  new_word += '('
          
          return new_word
      

      【讨论】:

        【解决方案3】:

        另一种解决方案。从一组(唯一)字符开始,遍历字符串中的字符,从该集中删除字符,如果它已经被删除,那么它必须是重复的。使用它来构建一组重复的字符。

        def duplicate_encode(word):
            word = word.upper()
            s = set(word)
            dups = set()
        
            for char in word:
                if char in s:
                    s.remove(char)
                else:
                    dups.add(char)
        
            return "".join(")" if char in dups else "("
                           for char in word)
        
        print(duplicate_encode("'yy! R)!QvdG'"))
        

        给予:

        ))))((()(((()
        

        【讨论】:

        • 这难道不是在 O(n^2) 时间内做同样的事情吗(如果 char 在每个字符的 dups 中)可以在 O(n) 时间内轻松完成?除非我看错了,否则这很糟糕。
        • @Ayush 不,因为 dups 是一个集合,所以查找是 O(1)。如果 dups 是一个列表,那么你是正确的。
        • 啊,这就是我所缺少的。谢谢
        • @Ayush 在wiki.python.org/moin/TimeComplexity 他们声明“平均情况”是 O(1),尽管“最坏情况”集合查找是 O(n)。我认为这是针对具有大量哈希冲突的病态不良情况。有趣的是,维基百科对“病态”的讨论正是引用了这个例子 - en.wikipedia.org/wiki/…
        • 对,虽然我相信所有这些都与集合本身无关,并且可以说是一般的散列,是吗?
        猜你喜欢
        • 2019-08-16
        • 1970-01-01
        • 2011-04-10
        • 2011-06-27
        • 2012-02-16
        • 2012-10-28
        • 2015-05-29
        • 2022-01-10
        • 2020-12-16
        相关资源
        最近更新 更多