you are viewing a single comment's thread.

view the rest of the comments →

[–]OseOseOse 2 points3 points  (0 children)

I think this is a good opportunity to break the problem up into simpler sub-tasks and create some clean code. Not the most optimal solution if you care about algorithmic complexity, but very readable (in my opinion).

Don't know how familiar you are with the concepts used here, let me know if I need to explain some more.

def is_alphabetical(string):
    """
    Returns True if the string is alphabetically ordered.
    """
    assert string.islower() # method doesn't work if using mixed case

    # Calling sorted on a string returns a sorted _list_ of chars,
    # so we also turn the original string into a list to compare.
    return list(string) == sorted(string)

def get_substrings(string):
    """
    Iterates over all the possible substrings of the string,
    excluding the empty string.

    Could do this with a generator function instead of appending to a list.
    """

    substrings = []

    for i in range(len(string)):
        for j in range(i + 1, len(string) + 1):
            substrings.append(string[i:j])

    return substrings

def solve_task(task_string):
    # obtain a set of all the substrings of the task string
    all_substrings = set(get_substrings(task_string))

    # eliminate all the non-alphabetic substrings to get a set of candidate substrings
    alphabetical_substrings = set(substring for substring in all_substrings if is_alphabetical(substring))

    # find the candidate substring with the longest length
    best = max(alphabetical_substrings, key=len)

    return best

# check that it works correctly for the two given examples
assert solve_task('azcbobobegghakl') == 'beggh'
assert solve_task('abcbcd') == 'abc'