Letters are in ascending order within the String

I need to create a program in python to create a list and find the numbers of The letters in the sequences 'abc', 'adz' are in ascending order, but the letters in the sequences 'aaa' and 'ghh' are not. That is, the first letter in the sequence must be less than the second letter and the second must be less than the third letter in order for the letters to be in ascending order. I already tried sorted() function but it is just sorting the complete list.

2 answers

  • answered 2017-06-17 18:34 Denis Kuzin

    1.Transform letters to ASCII. 2.Check the order is ascending or not

    def check_word(word):
        encoding = 0
        for letter in word:
            if ord(letter) > encoding:
                encoding = ord(letter)
            else:
                return False
        return True
    

    Results:

    check_word("abcds")
    

    True

    check_word("aacds")
    

    False

  • answered 2017-06-17 18:34 timotree

    I believe the function you're looking for is:

    def is_ascending(text):
        return list(text) == sorted(text) and len(text) == len(set(text)) # set removes duplicates
        # If it is alphabetical and there are no duplicates.
    

    Using this function, the code:

    for try_value in ("abc", "adz", "aaa", "ghh"):
        print(try_value, is_ascending(try_value))
    

    prints:

    abc True
    adz True
    aaa False
    ghh False