简体   繁体   中英

How to find the longest repeating sequence using python

I went through an interview, where they asked me to print the longest repeated character sequence.

I got stuck is there any way to get it?

But my code prints only the count of characters present in a string is there any approach to get the expected output

import pandas as pd
import collections

a   = 'abcxyzaaaabbbbbbb'
lst = collections.Counter(a)
df  = pd.Series(lst)
df

Expected output :

bbbbbbb

How to add logic to in above code?

A regex solution:

max(re.split(r'((.)\2*)', a), key=len)

Or without library help (but less efficient):

s = ''
max((s := s * (c in s) + c for c in a), key=len)

Both compute the string 'bbbbbbb' .

Without any modules, you could use a comprehension to go backward through possible sizes and get the first character multiplication that is present in the string:

next(c*s for s in range(len(a),0,-1) for c in a if c*s in a)

That's quite bad in terms of efficiency though

another approach would be to detect the positions of letter changes and take the longest subrange from those

chg = [i for i,(x,y) in enumerate(zip(a,a[1:]),1) if x!=y]
s,e = max(zip([0]+chg,chg+[len(a)]),key=lambda se:se[1]-se[0])
longest = a[s:e]

Of course a basic for-loop solution will also work:

si,sc = 0,"" # current streak (start, character)
ls,le = 0,0  # longest streak (start, end)
for i,c in enumerate(a+" "):      # extra space to force out last char.
    if i-si > le-ls: ls,le = si,i # new longest
    if sc != c:      si,sc = i,c  # new streak
longest = a[ls:le]

print(longest) # bbbbbbb

A more long winded solution, picked wholesale from:
maximum-consecutive-repeating-character-string

def maxRepeating(str):
 
    len_s = len(str)
    count = 0
 
    # Find the maximum repeating
    # character starting from str[i]
    res = str[0]
    for i in range(len_s):
         
        cur_count = 1
        for j in range(i + 1, len_s):
            if (str[i] != str[j]):
                break
            cur_count += 1
 
        # Update result if required
        if cur_count > count :
            count = cur_count
            res = str[i]
    return res, count
 
# Driver code
if __name__ == "__main__":
    str = "abcxyzaaaabbbbbbb"
    print(maxRepeating(str))

Solution:

('b', 7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM