Skip to content

Instantly share code, notes, and snippets.

@grahambinns
Last active December 28, 2015 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grahambinns/85b0d201a2c5f1fc48ea to your computer and use it in GitHub Desktop.
Save grahambinns/85b0d201a2c5f1fc48ea to your computer and use it in GitHub Desktop.
"""A script to find the longest word with all letters in alphabetical order."""
import sys
import string
DICTIONARY = "/usr/share/dict/british-english"
LETTERS = string.lowercase
def len_letters(word):
"""Return the length of a word counting only its letters.
>>> len_letters("graham's")
7
"""
return len([char for char in word if char in LETTERS])
def find_longest_ordered_word(words):
"""Find and return the longest word in `words` whose letters are ordered.
:param words: A list of words.
:return: The longest word in `words` whose letters are ordered
alphabetically.
>>> find_longest_ordered_word(["alphabet", "almost"])
'almost'
"""
ordered_words = set()
for word in words:
word = word.lower().strip()
if word.endswith("'s"):
continue
last_char_index = None
is_ordered = True
for character in word:
if character not in LETTERS:
# Discard any non A-Z characters.
continue
if LETTERS.index(character) > last_char_index:
last_char_index = LETTERS.index(character)
else:
is_ordered = False
if is_ordered:
ordered_words.add(word)
longest_ordered_word = ""
longest_ordered_words = set()
for ordered_word in ordered_words:
if len_letters(ordered_word) == len_letters(longest_ordered_word):
longest_ordered_words.add(ordered_word)
elif len_letters(ordered_word) > len_letters(longest_ordered_word):
longest_ordered_word = ordered_word
longest_ordered_words = set()
longest_ordered_words.add(ordered_word)
if len(longest_ordered_words) == 1:
return (longest_ordered_word, 1)
else:
return (
", ".join(
"{0} ({1})".format(word, len_letters(word))
for word in sorted(longest_ordered_words)),
len(longest_ordered_words))
if __name__ == "__main__":
with open(DICTIONARY, "r") as dictionary_file:
words = dictionary_file.readlines()
if "--reverse" in sys.argv:
# Reverse the LETTERS list so that 'z' is at the start of the
# alphabet and so on.
LETTERS = LETTERS[::-1]
words, count = find_longest_ordered_word(words)
print("Found {0} longest ordered words:".format(count))
print(words)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment