【问题标题】:Python counts the number of substrings that begin with a character and ends with anotherPython计算以一个字符开头并以另一个字符结尾的子字符串的数量
【发布时间】:2017-09-01 23:53:15
【问题描述】:

例如,给定输入字符串“CAXAAYXZA”,有四个以“A”开头并以“X”结尾的子字符串,即:“AX”、“AXAAYX”、“AAYX”和“AYX”。

【问题讨论】:

标签: python count substring


【解决方案1】:
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))

一种您可以做到这一点的方法

【讨论】:

    【解决方案2】:

    您可以应用正则表达式并搜索每个长度的组:

    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))
    

    【讨论】:

      【解决方案3】:
      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']

      斧头

      AXAAYX

      AAYX

      AYX

      【讨论】:

      • 请点赞,如果你用过,我在这上面浪费了一些时间。
      猜你喜欢
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 2019-08-26
      • 2021-10-24
      • 2016-12-21
      • 2017-04-18
      相关资源
      最近更新 更多