面试题答案
一键面试实现思路
- 利用正则表达式识别字符串中形如
'word1{3,5}word2'
的子串。 - 从识别出的子串中提取闭包操作符指定的频数范围,并统计每个范围出现的次数。
代码逻辑
- 导入
re
模块用于正则表达式操作。 - 定义函数,接收字符串列表作为参数。
- 使用正则表达式匹配符合格式的子串。
- 遍历匹配到的子串,提取频数范围并更新统计字典。
- 返回包含子串及其频数范围统计的结果。
代码示例
import re
def count_substring_ranges(str_list):
result = {}
pattern = re.compile(r'(\w+\{\d+,\d+\}\w+)')
for string in str_list:
matches = pattern.findall(string)
for match in matches:
range_str = re.search(r'\{(\d+,\d+)\}', match).group(1)
if match not in result:
result[match] = {range_str: 1}
else:
if range_str in result[match]:
result[match][range_str] += 1
else:
result[match][range_str] = 1
return result
你可以使用以下方式调用这个函数:
str_list = ["test{2,4}example", "test{2,4}example", "other{1,3}word"]
print(count_substring_ranges(str_list))