例如,给定输入字符串“CAXAAYXZA”,有四个以“A”开头并以“X”结尾的子串,即:“AX”,“AXAAYX”,“AAYX”和“AYX”。
答案 0 :(得分:0)
s = "CAXAAYXZA"
a = numpy.array(list(s))
start_indexes= numpy.where(a=='A')[0]
end_indexes= numpy.where(a=='X')[0]
print(sum(1 for i in start_indexes for j in end_indexes if i < j))
是一种方式,你可以做到这一点
答案 1 :(得分:0)
您可以应用正则表达式并搜索每个长度的组:
s = 'CAXAAYXZA'
n = sum(len(re.findall('(A\w{%i}X)' % i, s)) for i in range(len(s)))
执行后,n
在这种情况下将等于4
。或者以其扩展形式:
n = 0
for i in range(len(s)):
# Increase the total by the groups at i
n += len(re.findall('(A\w{%i}X)' % i, s))
答案 2 :(得分:0)
print "DO YOUR ASSIGNMENTS BY YOURSELF"
string="CAXAAYXZA"
string_char=list(string)
string_length=len(string_char)
print(string_char)
char_first="A"
char_second="X"
for i in range(0,string_length):
for b in range(i,string_length):
if(string_char[i]==char_first and string_char[b]==char_second):
list=[]
for z in range(i,b+1):
list.append(string_char[z])
print(''.join(list))
输出:
由你自己完成作业
['C','A','X','A','A','Y','X','Z','A']
AX
AXAAYX
AAYX
AYX