Re: the telegram problem: concurrency simplifies it (in Python)
Dave Long <[email protected]>
| Newsgroups | gmane.culture.people.kragen.discuss |
|---|---|
| Message-ID | <[email protected]> |
Granted, decoupling producer and consumer can often be useful (what
if, instead of enjoying a file abstraction, we were formatting words
which could be broken across network packets or disk blocks?) but I'm
not sure it applies in this case. The 1960's logic seems relatively
straightforward even without generators (although it does make use of
"magic" behavior from print, presumably exactly for this
application), and the functional approach still iterates from left-to-
right, even though the word-appending operation is associative and
hence in principle could be approached more concurrently.
-Dave
via "control break" programming:
:: :: ::
#!/usr/bin/python
"Telegram problem, aka fmt."
import sys
def telegram_control_break(infile, maxwidth):
"""A procedural version with minimal loop state
This is what you get if you're writing a program to solve the
problem about 50 years ago.
"""
xpos = 0
for line in infile:
for word in line.split():
if xpos + len(word) > maxwidth:
print
xpos = 0
print word,
xpos += len(word) + 1
print
if __name__ == '__main__':
telegram_control_break(sys.stdin, 72)
:: :: ::
or more functionally:
:: :: ::
#!/usr/bin/python
"Telegram problem, aka fmt."
bol = lambda s : ('\n'+s).rindex('\n')-1
fold = lambda (s,m),w: (s+" \n"[len(s)+len(w)-bol(s)>m]+w, m)
tgram_ = lambda ws,m : reduce(fold, ws[1:], (ws[0], m))[0]
tgram = lambda f,m : tgram_(f.read().split(),m)
if __name__ == '__main__':
import sys
print tgram(sys.stdin, 72)
:: :: ::
--
To unsubscribe: http://lists.canonical.org/mailman/listinfo/kragen-discuss