首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >对字符串的子字符串计数有限制

对字符串的子字符串计数有限制
EN

Stack Overflow用户
提问于 2020-09-23 06:10:38
回答 1查看 60关注 0票数 3

我有一根绳子和一本字典。我需要计算给定字符串的子字符串的数量,该字符串的字母数(和字母数)不超过字典中的字母数。我只计算了15个子字符串(2a +4b +1d + 2ba + 2ab +bd +db +abc +dba),但我不能编写程序。需要升级(我希望它只需要其他条件)

代码语言:javascript
复制
string = 'babdbabcce'
dict= {'a':1,'b':1,'d':1}
counter= 0
answer = 0

for i in range(len(string)):
    for j in dict:
        if string[i] == j:
            if dict[j] > 0:
                dict[j] = dict[j] - 1
                counter+= 1
                answer+= counter
#             else:                  
print(answer)
EN

Stack Overflow用户

回答已采纳

发布于 2020-09-23 06:51:13

似乎您要在另一个字符串中查找字符串(包括其中的子字符串)的排列,因此使用字典构建字符串,然后加载排列,然后计算另一个字符串中的排列。请注意,这可能不是最有效的解决方案,但它是有效的。

示例代码:

代码语言:javascript
复制
import itertools
import re

string_to_look_into = 'babdbabcce'
dict= {'a':1,'b':1,'d':1}

permutation_string = ''
for c, n in dict.items():
    permutation_string += c * n


permutations = itertools.permutations(permutation_string)
matches_to_count = set()
for perm in permutations:
    for i in range(1, len(perm)+1):
        matches_to_count.add(''.join(perm[:i]))


sum_dict = {} # to verify matches
sum = 0
for item in matches_to_count:
    count = len(re.findall(item, string_to_look_into))
    sum_dict[item] = count
    sum += count


print(sum)
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64018335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档