Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting abecedarian words in a list: Python

Tags:

python

list

Working on a very common problem to identify whether word is abecedarian (all letters in alphabetical order). I can do one word in several ways as discovered in "Think Python"; but, would like to be able to iterate through a list of words determining which are abecedarian and counting those that are.

def start():
    lines= []
    words= []
    for line in open('word_test1.txt'):
        lines.append(line.strip())
    numlines=len(lines)
    count = 0

    for word in lines[:]:
        i = 0
        while i < len(word)-1:
            if word[i+1] < word[i]:
                return 
            i = i+1
        print (word)
    count= count + 1
    print (count)
start()

I think my problem lies with the "return" in the "while i" loop. In the list I'm using there are at least three abecedarian words. The above code reads the first two (which are the first entries), prints them, counts them but on the following non-abecedarian word breaks out of the loop and ends the program.

I'm new at programming and this has taken me several hours over a couple of days.

like image 657
h-man Avatar asked Dec 07 '22 15:12

h-man


1 Answers

No need for low level programming on this one :-)

def is_abcedarian(s):
    'Determine whether the characters are in alphabetical order'
    return list(s) == sorted(s)

The use filter to run over a list of words:

>>> filter(is_abcedarian, ['apple', 'bee', 'amp', 'sun'])
['bee', 'amp']
like image 141
Raymond Hettinger Avatar answered Dec 09 '22 14:12

Raymond Hettinger