【问题标题】:Finding the longest substring of consecutive letters in python在python中找到最长的连续字母子串
【发布时间】:2019-04-27 16:34:29
【问题描述】:

我想用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()

我该如何解决这个问题?

【问题讨论】:

  • 将您的标题和描述更改为longest ALPHABETICAL substring
  • "Attempt" .. 我明白你在那里做了什么。

标签: python regex python-3.x


【解决方案1】:
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.

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多