2

I have a text file full of words. I need to go through the text file and count the number of words that are spelled in alphabetical order. I am struggling to think of way to figure out if a word is in alphabetical order.

I have already looked around and have seen that it can be done with sorted. However, we haven't yet learned about sort in class so I can't use it. Help/tips much appreciated.

Do I need to do something like assigning each letter of the alphabet a number?

4

2 回答 2

5

A word is in alphabetical order if (and only if) each adjacent pair of its letters is in alphabetical order.

于 2012-07-09T01:07:48.687 回答
5

Believe it or not, all characters are already implicitly assigned a number: their ASCII character codes. You can access them by using the ord() function, or compare them directly:

>>> "a" > "b"
False

>>> "b" > "a"
True

Beware though, capital letters are coded 65 - 90, while lowercase letters are coded 97 - 122, so:

>>> "C" > "b"
False

You have to ensure that you are comparing all uppercase or all lowercase letters.

Here's one possible function that uses the above information to check if a given string is in alphabetical order, just to get you started:

def isAlphabetical(word):
    for i in xrange(len(word) - 1):
        if word[i] > word[i+1]:
            return False
    return True
于 2012-07-09T01:29:01.573 回答