【问题标题】:Python count a subsequence in a stringPython计算字符串中的子序列
【发布时间】:2021-11-11 09:14:03
【问题描述】:

我的练习包括对二进制字符串中的子序列进行计数,但我不能使用 count 方法,因为例如,如果字符串 '10010000' 中有子序列 '00',则 count 方法将返回 ' 3',但正确答案是'4'。

我试过了:

def subseq_uguale(stringa,testo,lunghezza):
    f=0
    for i in range(len(testo)-lunghezza+1):
        confronta=''
        for j in range(lunghezza):
            confronta+=testo[i+j]
        if confronta==stringa:
            f+=1
    return f

其中 'lunghezza' 是子序列的长度,'testo' 是序列,'stringa' 是子序列。但这需要太多时间! 我该如何解决这个问题?

【问题讨论】:

标签: python string count subsequence


【解决方案1】:

试试这个

def subseq_uguale(stringa, testo):
    f=0
    for i in range(len(testo)+1-len(stringa)):
        if stringa==testo[i:i+len(stringa)]:
            f+=1
    return f

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多