wow! (generators) - suggestion (yield saved)

Alex Martelli aleaxit at yahoo.com
Mon Aug 6 11:31:29 EDT 2001


"Roman Suzi" <rnd at onego.ru> wrote in message
news:mailman.997020711.25657.python-list at python.org...
    ...
> >What's wrong with:
> >
> >import calendar, string
> >def calt(year, month):
> >    month_cal = calendar.monthcalendar(year, month)
> >    scal = ''
> >    scal += "<B>%s.%s</B>" % (month, year)
> >    scal += "<TABLE BORDER=1>"
> >    for week in month_cal:
> >      scal += "\n<TR>"
> >      for day in week:
> >        scal += "<TD>%s</TD>" % (day or " ")
> >      scal += "</TR>"
> >    scal += "</TABLE>"
> >    return scal
>
> Except for long table you get far too many concatenations.
> (Well, calendar is not that long).

It's still inferior style to build up a big-gish string by += of
a lot of small ones, but that's easily fixed, e.g (warning,
untested code):

def calt(year, month):
    scal = ["<B>%s.%s</B>" % (month, year),
               "<TABLE BORDER=1>"]
    for week in month_cal:
        scal.append("\n<TR>")
        scal.extend(["<TD>%s</TD>" % (day or " ")
            for day in week])
        scal.append("</TR>")
    scal.append("</TABLE>")
    return ''.join(scal)


Alex






More information about the Python-list mailing list