Finding the longest substring of consecutive letters in python

from itertools import count

def f(input_string):
    maxsubstr = input_string[0:0]
    for start in range(len(input_string)):
        for end in count(start + len(maxsubstr) + 1):
            substr = input_string[start:end]
            if len(set(substr)) != (end - start):
                break
            if (ord(max(substr)) - ord(min(substr)) + 1) == len(substr):
                maxsubstr = substr
    print ('The longest substring of consecutive letters has a length of {}.'.format(len(maxsubstr)))
    print ('The leftmost such substring is {}.'.format(maxsubstr))

f('x')
f('xy')
f('ababcuvwaba')
f('abbcedffghiefghiaaabbcdefgg')
f('abcabccdefcdefghacdef')

output:

The longest substring of consecutive letters has a length of 1.
The leftmost such substring is x.
The longest substring of consecutive letters has a length of 2.
The leftmost such substring is xy.
The longest substring of consecutive letters has a length of 3.
The leftmost such substring is abc.
The longest substring of consecutive letters has a length of 6.
The leftmost such substring is bcdefg.
The longest substring of consecutive letters has a length of 6.
The leftmost such substring is cdefgh.

Leave a Comment