Created
August 14, 2012 07:06
-
-
Save dvoiss/3347094 to your computer and use it in GitHub Desktop.
Reddit Daily Programmer Challenge: Print a Calendar
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
#!/usr/bin/python | |
# For the reddit daily programmer challenge | |
# Challenge: http://www.reddit.com/r/dailyprogrammer/comments/y5svk/8132012_challenge_88_intermediate_printing_out_a/ | |
# Solution: http://www.reddit.com/r/dailyprogrammer/comments/y5svk/8132012_challenge_88_intermediate_printing_out_a/c5soy7s | |
# run code at http://ideone.com/yFOA4 | |
# by @dvoiss on github / @daveasaurus on reddit | |
# Two variations: | |
# the first simply uses the calendar module's print capability: | |
# the second uses calendar module for localized month name and day abbreviations | |
# and for getting the days in a month, the output is printed using format strings | |
import calendar | |
# 1. use built in method: | |
print '\n'.join( calendar.month(2012,1).split('\n') ) | |
# 2. see reddit comment for more info | |
separator_string = '+' + '-'*20 + '+' | |
def print_cal(month, year): | |
month_days = [ '' if i == 0 else str(i) for i in calendar.Calendar(0).itermonthdays(year, month) ] | |
print separator_string + '\n|' + str.center( calendar.month_name[month], 20 ) + '|\n' + separator_string | |
print '|' + "".join(['{' + str(i) + ':<2}|' for i in range(0, 7) ]).format(*map(lambda x: x[0] + ' ', calendar.day_abbr)) | |
print separator_string | |
print "".join([('|{' if j % 7 == 0 else '{') + str(i + j + (6 * i)) + ':<2}|' | |
+ ('\n' if j % 7 == 6 and i != (len(month_days) / 7 - 1) else '') for i in range(0, len(month_days) / 7) for j in range(0, 7)]).format(*month_days) | |
print separator_string | |
print_cal(1, 2012) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OUTPUT: