【发布时间】:2021-11-24 21:24:18
【问题描述】:
需要根据给定的模式创建一个字符串。
如果模式是222243243,则需要创建的字符串是“2{4,6}[43]+2{1,3}[43]+”。 创建上述字符串的逻辑是,检查模式中有多少个 2 集合并计算它们并添加更多两个 2。这里包含两组 2。第一个包含 4 个 2,第二个部分包含 1 个 2。所以第一个 2 可以是 4 到 6(4+2) 个 2,第二个 2 可以是 1 到 3(1+2)。当有 3 或 4 时,[43]+ 需要添加。
工作原理:
import re
data='222243243'
TwosStart=[]#contains twos start positions
TwosEnd=[]#contains twos end positions
TwoLength=[]#number of 2's sets
for match in re.finditer('2+', data):
s = match.start()#2's start position
e = match.end()#2's end position
d=e-s
print(s,e,d)
TwosStart.append(s)
TwosEnd.append(e)
TwoLength.append(d)
所以使用上面的代码,我知道给定模式中有多少个 2 组以及它们的开始和结束位置。但我不知道使用上述信息自动创建一个字符串。
例如:
if pattern '222243243' string should be "2{4,6}[43]+2{1,3}[43]+"
if pattern '222432243' string should be "2{3,5}[43]+2{2,4}[43]+"
if pattern '22432432243' string should be "2{2,4}[43]+2{1,3}[43]+2{2,4}[43]+"
【问题讨论】:
标签: python python-3.x string logic