I really have no idea how to go about this. So far all I have is this:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
I am supposed to go through a text file and count the number of words in alphabetical order.
I can’t do
if word in alphabet:
because that requires the word to actually have all of those letters in order.
To clarify: ‘blow’ would pass the test and ‘suck’ would not.
I have a list of thousands of words, I need to go through the entire list and count the numbers of words that are in alphabetical order. Sorry for any prior confusion.
Very simple:
So know we can define the predicate we need:
And apply it to a list:
From there it’s not a large step to counting the results 🙂 There’s some other things to consider:
O(n*log n), although this problem could easily be solved inO(n). This is probably okay because words usually have a bounded number of characters andsortedis implemented in C and thus very fastsum(1 for w in w if ...)trick, which uses a generator expression instead of building a list.