Skip to content

Instantly share code, notes, and snippets.

@dvoiss
Created August 14, 2012 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvoiss/3347094 to your computer and use it in GitHub Desktop.
Save dvoiss/3347094 to your computer and use it in GitHub Desktop.
Reddit Daily Programmer Challenge: Print a Calendar
#!/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)
@dvoiss
Copy link
Author

dvoiss commented Aug 14, 2012

OUTPUT:

    January 2012
Mo Tu We Th Fr Sa Su
                   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 31

+--------------------+
|      January       |
+--------------------+
|M |T |W |T |F |S |S |
+--------------------+
|  |  |  |  |  |  |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|31|  |  |  |  |  |
+--------------------+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment