Comparing characters in a string sequentially in Python

前端 未结 2 1564
别那么骄傲
别那么骄傲 2020-12-06 20:22

I am trying to figure out how to compare a character in a string to the next character in the string. For example, if I have a string:

s = \'vzcbotdebobeggg         


        
相关标签:
2条回答
  • 2020-12-06 21:11

    How about this:

    def longest_ascending(s):
        matches = []
        current = [s[0]]
        for index, character in enumerate(s[1:]):
            if character >= s[index]:
                current.append(character)
            else:
                matches.append(current)
                current = [character]
        matches.append(current)
        return "".join(max(matches, key=len))
    

    Explanation:

    • matches is a list of all substrings with "ascending" characters.
    • current is the substring of ascending characters being built as we iterate through the string. We start out with the first character of the string.
    • We now iterate through the remaining string character by character. enumerate() helps us keep track of the index of the previous character (because the enumeration starts at 0 and we iterate the string from the second character onwards).
    • If the current character is "greater or equal" to the previous one, we add it to the current substring and move on.
    • If not, we add the current substring to the list of substrings, and seed the next substring with the current character.
    • After the iteration is over, don't forget to add the current substring to the list as well.
    0 讨论(0)
  • 2020-12-06 21:15

    This is less obvious, but seems to work:

    seq = "vzcbotdebobeggglakyl"
    
    import itertools
    result = max(
        (
            list(next(sub)) + [b for a, b in sub]
            for ascending, sub in itertools.groupby(zip(seq,seq[1:]), lambda x: x[0] <= x[1])
            if ascending
        ),
        key=len
    )
    
    print ''.join(result)
    
    0 讨论(0)
提交回复
热议问题