Ordered words: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Added a version using functools.reduce in place of `for` and `sort`)
(→‎Python: As a fold: (Slight simplification, dropping dropwhile))
Line 3,102: Line 3,102:
<lang python>'''The longest ordered words in a list'''
<lang python>'''The longest ordered words in a list'''


from itertools import dropwhile
from functools import reduce
from functools import reduce
import urllib.request
import urllib.request
import operator




Line 3,112: Line 3,110:
'''The longest ordered words in a given list.
'''The longest ordered words in a given list.
'''
'''
lng, xs = reduce(triage, ws, (0, []))
return reduce(triage, ws, (0, []))[1]
gt = curry(operator.gt)
return dropwhile(
compose((gt)(lng))(len),
xs
)




Line 3,123: Line 3,116:
def triage(nxs, w):
def triage(nxs, w):
'''The maximum length seen for an ordered word,
'''The maximum length seen for an ordered word,
and the long ordered words seen so far,
and the ordered words of this length seen so far.
including this word if it is both ordered and
no shorter than the maximum so far.
'''
'''
n, xs = nxs
n, xs = nxs
lng = len(w)
lng = len(w)
return (
return (
(lng, xs + [w]) if ordWord(w) else nxs
(lng, ([w] if n != lng else xs + [w])) if (
ordWord(w)
) else nxs
) if lng >= n else nxs
) if lng >= n else nxs


Line 3,151: Line 3,144:




# TEST ---
# TEST ----------------------------------------------------
if __name__ == '__main__':
def main():
'''Test with an on-line word list.'''
print(
print(
'\n'.join(longestOrds(
'\n'.join(longestOrds(
Line 3,160: Line 3,152:
).read().decode("utf-8").split()
).read().decode("utf-8").split()
))
))
)
)</lang>


# GENERIC -------------------------------------------------

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))


# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
'''A curried function derived
from an uncurried function.'''
return lambda a: lambda b: f(a, b)


# MAIN ---
if __name__ == '__main__':
main()</lang>
{{Out}}
{{Out}}
<pre>abbott
<pre>abbott