告诉我我的字串问题的代码有什么问题?

问题描述 投票:1回答:1
s='cbaebabacd'
p='abc'
l=[]
answer = list()
count = 0
l = list([s[i] for i in range(j,j+len(p))] for j in range(len(s)-len(p)+1))
for i in l:
    for j in range(len(p)):
        k=list(p)
        if i[j] in k:
            k.remove(i[j])
            if len(k)==0:
               answer.append(count)
            else:
                continue
        count += 1
        break
print(answer)

这段代码的输出是"[]",但我认为对于字谜子串问题,它的输出应该是"[0,6]"。

python-3.x list list-comprehension
1个回答
1
投票

唯一的问题是 k=list(p),它不应该在内部循环中,而应该在它之前。

s='cbaebabacd'
p='abc'
l=[]
answer = list()
count = 0
l = list([s[i] for i in range(j,j+len(p))] for j in range(len(s)-len(p)+1))
for i in l:
    k=list(p)
    for j in range(len(p)):
        if i[j] in k:
            k.remove(i[j])
            if len(k)==0:
               answer.append(count)
            else:
                continue
        count += 1
        break
print(answer)

输出。

[0, 6]
© www.soinside.com 2019 - 2024. All rights reserved.