Ordered Words
July 14, 2015
An ordered word is one in which the letters in the word appear in alphabetic order; for instance, dirt and knotty are ordered words, praxis is not.
Your task is to write a program to find the longest ordered word in a dictionary. When you are finished, you are welcome to read a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Python.
Added capitals, no requirement there. Otherwise add s.lower() in comparisons.
Scala:
val words = List(“abc”,”cba”, “billowy”, “deglory”, “egilops”, “aZ”, “Za”)
val orderedWords = words.filter(x=>x.toLowerCase==x.toLowerCase.sorted)
val longest= orderedWords.map(x => x.size).max
orderedWords.filter(x=>x.size==longest)
//> res0: List[String] = List(billowy, deglory, egilops)
@Rutger: you forgot to select the longest
Longest:
print sorted([word for word in [‘abc’, ‘cba’, ‘billowy’, ‘deglory’, ‘egilops’, ‘aZ’, ‘Za’] if sorted(word) == list(word)], key=len, reverse=True)[0]
Two more solutions in Python. The first is using a trie. Generatting the trie costs much time, but finding the word is superfast.
According to my sample program, the longest such word in my /usr/share/dict/words file is “Babbitt”.
Some solutions in (Guile) Scheme.
A Haskell version. In order to avoid having to retain all the ordered words in
memory (as would always be the case when sorting by length) I use maxsBy
to keep only the longest ordered words seen so far. Of course, if all the ordered
words have the same length we still lose…
Using as input the dictionary on a Mac:
Solution in R7RS Scheme with SRFI 95.
https://notabug.org/PangolinTurtle/praxis-solutions/raw/master/2015-07-14.scm
scheme@(guile-user)> (ordered-words “/usr/share/dict/words”)
$31 = 7
$32 = (“egilops” “billowy” “begorry” “beefily” “alloquy” “Adelops”)
[…] My racket solution to the Ordered Words Problem on Programming Praxis: […]