python - Faster way to print all starting indices of a substring in a string, including overlapping occurences -


i'm trying answer homework question: find occurrences of pattern in string. different occurrences of substring can overlap each other.

sample 1.

input:

tacg

gt

output:

explanation: pattern longer text , hence has no occurrences in text.

sample 2.

input:

ata

atata

output:

0 2

explanation: pattern appears @ positions 1 , 3 (and these 2 occurrences overlap each other).

sample 3.

atat

gatatatgcatatactt

output:

1 3 9

explanation: pattern appears @ positions 1, 3, , 9 in text.

the answer i'm submitting one:

def all_indices(text, pattern):     = text.find(pattern)     while >= 0:         print(i, end=' ')         = text.find(pattern, + 1)   if __name__ == '__main__':     text = input()     pattern = input()     all_indices(text, pattern) 

however, code failing final test cases:

failed case #63/64: time limit exceeded (time used: 7.98/4.00, memory used: 77647872/536870912.)

the online judge knows i'm sending answer in python, , has different time limits different languages.

i have searched quite bit other answers , approaches: regexes, suffix trees, aho-corasick... far of them underperform simple solution (maybe because find implemented in c?).

so question is: there ways task faster?

if print slows program most, should try call little possible. quick , dirty solution problem:

def all_indices(string, pattern):     result = []     idx = string.find(pattern)     while idx >= 0:         result.append(str(idx))         idx = string.find(pattern, idx + 1)     return result  if __name__ == '__main__':     string = input()     pattern = input()     ' '.join(all_indices(string, pattern)) 

in future correctly identify part of code slowing down whole process can use python profilers


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -