【问题标题】:How to check if a substring contains all of the letters in "apple"如何检查子字符串是否包含“apple”中的所有字母
【发布时间】:2018-04-18 05:50:31
【问题描述】:

如果我有字符串 "axplpett" 我想返回 true,因为它的子字符串 "axplpe" 包含所有苹果的字母。

本来想用set方法,但是apple有重复字符。

【问题讨论】:

  • 为什么不对字符串的子串做一个简单的迭代,并检查字符串中是否包含子串的每个字母。

标签: python substring anagram


【解决方案1】:

就这么简单?

string = "axplpett"
test = "apple"
all(string.count(l) >= test.count(l) for l in test)

【讨论】:

    【解决方案2】:
    r = 'aapple'
    w = list('axplpett')
    try:
        for x in r:
            w.pop(w.index(x))
        print(True) # return True
    except ValueError:
        print(False) # return False
    

    【讨论】:

    • 不,在一般情况下你错了尝试“aaa”与“abc”:set(“aaa”)是{“a”},它包含在set(“abc”)中但没有子字符串“abc”的变位词是“aaa”的字谜
    • @Julien 重新设计了代码以严格控制每个字母的计数。
    【解决方案3】:

    也许是这样的:-

    def findsub (sub,main):
        l1 = [i for i in sub]
        l2 = [i for i in main]
        for item in l1:
            if item in l2:
                l2.remove(item)
            else:
                return False
        return True
    print(findsub('apple','appleccssfftt'))
    

    【讨论】:

      【解决方案4】:

      您可以通过Counter 轻松做到这一点。

      我们从测试字符串“axplpett”中的字母数中减去目标字符串“apple”中的字母数。目标字符串中不在测试字符串中的任何字母都将导致这些字母的计数为负数。然后我们否定该结果,这会去除正数或零计数,如果目标字符串包含在测试字符串中,则结果计数器将为空。

      from collections import Counter
      
      target = 'apple'
      test = 'axplpett'
      counts = Counter(test)
      counts.subtract(target)
      print(not -counts)
      
      counts = Counter('axplett')
      counts.subtract(target)
      print(not -counts)
      

      输出

      True
      False
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-08
        • 2020-12-12
        • 2015-01-04
        • 2019-06-07
        • 1970-01-01
        • 2011-07-11
        • 2012-02-22
        相关资源
        最近更新 更多