1

I am trying to iterate through a string and mark () around the longest repeated adjacent values. Example:

"344556(7777)5412"

max_run = "0"    
J = "34455677775412"
for x in range(len(J)-1):
    if J[x] == J[x+1]
      if J[x:x+2] > max_run:
          print( "(", end = "")
          max_run = J[x:x+2]
          print( ")", end = "")
          
emma.delia
  • 19
  • 4

4 Answers4

6

The method groupby from package itertools of the standard library sequentially group terms, then take the maximum.

import itertools as it

ref_string = "34455677775412"
max_squence = ''.join(max(list(j) for _, j in it.groupby(ref_string)))

print(ref_string.replace(max_squence, f'({max_squence})'))
cards
  • 2,194
  • 1
  • 3
  • 21
1

Love itertools, but as there is already a (nice) solution withgroupby, here is one with a classical loop:

J = "34455677775412"

run = []
prev = None
for pos, char in enumerate(J):
    if char == prev:
        run[-1][0] += 1
    else:
        run.append([1, pos])
    prev = char
print(run)
a,b = max(run, key=lambda x: x[0])

J[:b]+'('+J[b:b+a]+')'+J[b+a:]

output: '344556(7777)5412'

mozway
  • 81,317
  • 8
  • 19
  • 49
0

In case you can't use any standard library methods like groupby, here's a plain python implementation that does the same thing:

i = 0
max_start, max_end = 0, 0
J = "34455677775412"
# find the longest repeating sequence
while i < len(J):
    j = i
    while j < len(J) and J[j] == J[i]:
        j += 1
    max_start, max_end = max([(max_start, max_end), (i, j)], key=lambda e: e[1] - e[0])
    i = j
print(max_start, max_end, J[max_start:max_end])

J = J[:max_start] + "(" + J[max_start:max_end] + ")" + J[max_end:]  # insert the parentheses
print(J)

rdas
  • 18,048
  • 6
  • 31
  • 42
0

You could also use Python regex library re to achieve a similar solution to @cards's one

import re

J = "34455677775412"
pattern = r'(.)\1+'

longest_sequence = max([match.group() for match in re.finditer(pattern, J)])
print(J.replace(longest_sequence, f'({longest_sequence})'))
Marcos Blandim
  • 300
  • 1
  • 7