Нахождение самой длинной подстроки последовательных букв в питоне - PullRequest
0 голосов
/ 27 апреля 2019

Я хочу найти самую длинную подстроку последовательных букв, используя python.

Попытка

def f(word):
    '''
    Recall that if c is an ascii character then ord(c) returns its ascii code.
    Will be tested on nonempty strings of lowercase letters only.

    >>> f('x')
    The longest substring of consecutive letters has a length of 1.
    The leftmost such substring is x.
    >>> f('xy')
    The longest substring of consecutive letters has a length of 2.
    The leftmost such substring is xy.
    >>> f('ababcuvwaba')
    The longest substring of consecutive letters has a length of 3.
    The leftmost such substring is abc.
    >>> f('abbcedffghiefghiaaabbcdefgg')
    The longest substring of consecutive letters has a length of 6.
    The leftmost such substring is bcdefg.
    >>> f('abcabccdefcdefghacdef')
    The longest substring of consecutive letters has a length of 6.
    The leftmost such substring is cdefgh.
    '''
    desired_length = 0
    desired_substring = ''
    print(f'The longest substring of consecutive letters has a length of {desired_length}.')
    print(f'The leftmost such substring is {desired_substring}.')
if __name__ == '__main__':
    import doctest
    doctest.testmod()

Как мне решить эту проблему?

1 Ответ

1 голос
/ 27 апреля 2019
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')

выход:

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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...