【问题标题】:return a dictionary with a number of instances for each character返回一个字典,其中每个字符都有多个实例
【发布时间】:2021-10-27 10:26:36
【问题描述】:

该函数取两个字对应的两个字符串并返回 当且仅当一个是另一个的字谜,也就是说,如果单词是由 相同的字母,忽略大小写之间的差异以及之间的顺序 字符。

>>> eh_anagrama(’caso’, ’SaCo’)
True
>>> eh_anagrama(’caso’, ’casos’)
False

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    简单但对数线性的方法:

    def eh_anagrama(s1, s2):
        return sorted(s1.lower()) == sorted(s2.lower())
    

    更好的线性方法,使用collections.Counter

    from collections import Counter
    
    def eh_anagrama(s1, s2):
        return Counter(s1.lower()) == Counter(s2.lower())
    

    这样做的好处很可能只适用于非常长的字符串,因为排序是经过 C 语言优化的。

    【讨论】:

      【解决方案2】:

      如何在字典中使用结果和字符计数。

      代码

      def anagram(s1, s2):
          ana = sorted(s1.lower()) == sorted(s2.lower())
          
          d1 = {}
          d2 = {}
          for x in set(s1):  # Get unique char
              d1.update({x: s1.count(x)})  # Count each char
          for x in set(s2):
              d2.update({x: s2.count(x)})
      
          return {'anagram': ana, s1: d1, s2: d2}
      
      
      s1 = 'caso'
      s2 = 'SaCo'
      res1 = anagram(s1, s2)
      print(res1)
      
      s1 = 'caso'
      s2 = 'casos'
      res2 = anagram(s1, s2)
      print(res2)
      

      输出:

      {'anagram': True, 'caso': {'o': 1, 's': 1, 'c': 1, 'a': 1}, 'SaCo': {'o': 1, 'C': 1, 'a': 1, 'S': 1}}
      {'anagram': False, 'caso': {'o': 1, 's': 1, 'c': 1, 'a': 1}, 'casos': {'o': 1, 's': 2, 'c': 1, 'a': 1}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-10
        • 2014-11-26
        • 2019-04-22
        • 2014-05-21
        • 2021-12-24
        • 1970-01-01
        • 2017-01-04
        • 2017-11-23
        相关资源
        最近更新 更多