Last active
August 29, 2015 14:16
-
-
Save kwatch/d93f814a87aba7c8b59e to your computer and use it in GitHub Desktop.
1ヶ月分のカレンダーを表示する(その2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import sys | |
try: | |
xrange | |
except NameError: | |
xrange = range | |
def generate_days(ndays, wday): | |
""" | |
1ヶ月分の日を生成するジェネレータ関数。 | |
たとえば generate_days(30, 2) だと、 | |
None, None, 1, 2, 3, ..., 28, 29, 30, None, None, None | |
を生成する。 | |
""" | |
for _ in xrange(wday): | |
yield None | |
for i in xrange(1, ndays+1): | |
yield i | |
n = (wday + ndays) % 7 | |
if n < 7: | |
for _ in xrange(7 - n): | |
yield None | |
def generate_weeks(ndays, wday): | |
""" | |
1ヶ月分のデータを生成するジェネレータ。 | |
たとえば build_month(30, 2) なら | |
[None, None, 1, 2, 3, 4, 5], | |
[ 6, 7, 8, 9, 10, 11, 12], | |
[ 13, 14, 15, 16, 17, 18, 19], | |
[ 20, 21, 22, 23, 24, 25, 26], | |
[ 27, 28, 29, 30, None, None, None] | |
を生成する。 | |
""" | |
week = [] | |
for x in generate_days(ndays, wday): | |
week.append(x) | |
if len(week) == 7: | |
yield week | |
week = [] | |
assert week == [] | |
def render_weeks(weeks): | |
""" | |
1ヶ月分のデータを受け取り、HTMLテーブルを返す。 | |
""" | |
buf = [] | |
buf.append('''<table> | |
<thead> | |
<th>Mon</th> | |
<th>Tue</th> | |
<th>Wed</th> | |
<th>Thu</th> | |
<th>Fri</th> | |
<th>Sat</th> | |
<th>Sun</th> | |
</thead> | |
<tbody> | |
''') | |
for week in weeks: | |
buf.append( ' <tr>\n') | |
for day in week: | |
s = '' if day is None else str(day) # or: s = str(day or '') | |
buf.extend((' <td>', s, '</td>\n')) | |
buf.append( ' </tr>\n') | |
buf.append( ''' </tbody> | |
</table> | |
''') | |
return "".join(buf) | |
def print_calendar_month(ndays, wday): | |
""" | |
1ヶ月分のカレンダーを出力する。 | |
""" | |
html = render_weeks(generate_weeks(ndays, wday)) | |
print(html) | |
if __name__ == '__main__': | |
print_calendar_month(30, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment