0

I need to find the highest number of consecutive occurrence of a sub-string in a string for example in

s = "abccddababdd"
nof_ab = s.count('ab')

I want it to return

2

not

3

I tried the count function but it returns the total count of occurrence in the string not the highest number of consecutive occurrence

how can I do this?

  • 1
    Why are you looking for better option? – Poojan Feb 04 '20 at 16:12
  • @DeepSpace Its obviously looks like a typing error from OP. Otherwise `s.count` will not run at all. It will throw an error. – Poojan Feb 04 '20 at 16:18
  • `str.count` doesn't solve the problem either way since OP is specifically looking for the number of _longest consecutive_ occurrences, not _all_. – b_c Feb 04 '20 at 16:21
  • 1
    IMO, this question shouldn't have been closed as duplicate - OP isn't looking for a count of overlapping substrings. @atg you can use regex to do this (pardon the formatting): `import re; sub = 'ab'; len(max(re.findall(rf'(?:{sub})+', s))) // len(sub)`. This finds all occurrences of the substring (`sub`) occurring at least once, but repeating as much as possible. Then, it filters to the longest one of them (`max(...)`) and divides its length by the length of the substring, giving you the number of occurrences. – b_c Feb 04 '20 at 16:31
  • @DeepSpace yes, It's a typo I need the number of longest consecutive occurrences not all of them and not considering overlapping – AloneTheGreat Feb 04 '20 at 16:35
  • @b_c thanks for the help – AloneTheGreat Feb 04 '20 at 16:37

0 Answers0