Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果一个字符串与另一个字符串(包括Double Python-3.x)共享所有字符,则返回bool_Python_String_Python 3.x_Python 3.6 - Fatal编程技术网

如果一个字符串与另一个字符串(包括Double Python-3.x)共享所有字符,则返回bool

如果一个字符串与另一个字符串(包括Double Python-3.x)共享所有字符,则返回bool,python,string,python-3.x,python-3.6,Python,String,Python 3.x,Python 3.6,很抱歉,如果有人问过类似的问题,我找不到 我需要检查string\u a是否包含string\u b中的所有字符,包括非唯一字符 例1: ... string_a = 'baba' ... string_b = 'baaa' ... <solution here> False 我尝试了set()。所以我有这个: ... string_a = 'baba' ... string_b = 'baaa' ... return set(string_b) <= set(string_

很抱歉,如果有人问过类似的问题,我找不到

我需要检查
string\u a
是否包含
string\u b
中的所有字符,包括非唯一字符

例1:

... string_a = 'baba'
... string_b = 'baaa'
... <solution here>
False
我尝试了
set()。所以我有这个:

... string_a = 'baba'
... string_b = 'baaa'
... return set(string_b) <= set(string_a)
True
。。。字符串_a='baba'
... 字符串_b='baaa'

... 返回集(string_b)您要做的是将字符串解释为,并检查其中一个是否是另一个的子集。Python的多集表示法是:

不幸的是,
计数器
没有实现
is\u子集
方法,因此我们必须编写自己的方法。以下是两种方法:

def is_sub_multiset(haystack, needle):
    haystack = Counter(haystack)
    needle = Counter(needle)

    return not needle - haystack
    # OR
    # return all(haystack[elem] >= count for elem, count in needle.items())

对我来说,使用计数器作为解决方案似乎是最好的

首先对字符串_a中的所有字符进行计数,然后逐字符检查字符串_b并从计数器中减去字符,如果计数器=0,则计数失败。这允许我们在O(n)中得到一个解决方案,读取每个字符串一次

from collections import Counter

def is_subset(string_a, string_b):
  count = Counter(string_a)
  for c in string_b:
    if count[c] == 0:
      return False
    count[c] -= 1
  return True


print(is_subset('baba', 'baaa')) # =>False
print(is_subset('ababa', 'baaa')) # =>True
print(is_subset('aabb', 'd')) # =>False
print(is_subset('aabb', 'bbb')) # =>False
def is_sub_multiset(haystack, needle):
    haystack = Counter(haystack)
    needle = Counter(needle)

    return not needle - haystack
    # OR
    # return all(haystack[elem] >= count for elem, count in needle.items())
>>> is_sub_multiset('baba', 'baaa')
False
>>> is_sub_multiset('ababa', 'baaa')
True
from collections import Counter

def is_subset(string_a, string_b):
  count = Counter(string_a)
  for c in string_b:
    if count[c] == 0:
      return False
    count[c] -= 1
  return True


print(is_subset('baba', 'baaa')) # =>False
print(is_subset('ababa', 'baaa')) # =>True
print(is_subset('aabb', 'd')) # =>False
print(is_subset('aabb', 'bbb')) # =>False