Created
August 28, 2012 01:30
-
-
Save benjamingeiger/3494107 to your computer and use it in GitHub Desktop.
Python script to find the longest words with letters in reverse alphabetical order.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Remove non-alphabetic characters (hyphens, etc) from the word. | |
def strip_non_alpha(word): | |
return "".join([x for x in list(word.lower()) if (x >= 'a' and x <= 'z')]) | |
# Sort the letters in the word (in reverse). | |
def sort_letters(word): | |
letters = sorted(list(word)) | |
letters.reverse() | |
return "".join(letters) | |
# Read the list of words. | |
words = open("/Users/bgeiger/Downloads/enable1.txt", "r") | |
# Create a list of words that match. | |
sortedwords = [] | |
# For each word in the input list... | |
for word in words: | |
# ... take out the non-alphabetic characters... | |
word = strip_non_alpha(word) | |
# ... and if the letters are already sorted in the proper order... | |
if sort_letters(word) == word: | |
# ... add the word to the list. | |
sortedwords.append(word) | |
# Sort the completed list of words by length. | |
sortedwords.sort(key=len) | |
# Reverse the list, so the longest words come first. | |
sortedwords.reverse() | |
# Print the entire list. | |
print sortedwords |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment