ひさびさのプログラミング勉強
帰省から久しぶりのプログラミング勉強。帰省中のおよそ2週間はパソコンをほとんど使わなかったのでちょっと忘れかけてる・・・。やっぱり継続は大事だなあ。
というわけでリハビリを兼ねてプログラムを書いてみた。内容は任意の年、月、日を入力してその日の曜日を表示するプログラム。グレゴリオ暦を基にしてる。
def days_of_the_week(years,months,days): #1・2月は去年の13・14月とする if months < 3: years = years - 1 months = months + 12 #a <- years年3月1日の曜日に対応する数 a = 3 + years + years/4 - years/100 + years/400 #b <- 3月1日からmonths月1日までの日数 b = int(30.6 * (months - 3) + 0.5) #c <- 1日からdays日までの日数 c = days - 1 tmp = a + b + c dotw = tmp % 7 #Sunday=0,Monday=1,Tuesday=2,Wendesday=3, #Thursday=4,Friday=5,Saturday=6 とする if dotw == 0: print "It's Sunday" elif dotw == 1: print "It's Monday" elif dotw == 2: print "It's Tuesday" elif dotw == 3: print "It's Wednesday" elif dotw == 4: print "It's Thursday" elif dotw == 5: print "It's Friday" else: print "It's Saturday"
細かいアルゴリズムについては
アルゴリズム入門―C言語による計算 (Information & computing (92))
- 作者: 影井清一郎
- 出版社/メーカー: サイエンス社
- 発売日: 1997/04/01
- メディア: 単行本
- この商品を含むブログ (2件) を見る
実行結果例:
>>> days_of_the_week(2007,9,5)
It's Wednesday
※今日(2007年9月5日)>>> days_of_the_week(1929,10,24)
It's Thursday
※1929年10月24日ニューヨーク株式市場の株価暴落(暗黒の木曜日の日)>>> days_of_the_week(1987,10,19)
It's Monday
※1987年10月19日上と同じくニューヨーク株式市場の株価暴落(ブラックマンデーの日)>>> days_of_the_week(1452,4,15)
It's Thursday
※1452年4月15日レオナルド・ダ・ヴィンチの誕生日
ちなみに自分は木曜日生まれ。YUIっていうシンガーソングライターと同年齢・同誕生日らしい(ちなみに数学者エルデシュとも誕生日が同じ(`・ω・´))。あんまり音楽は聴かないけど、ちょっと応援してみようかなとか思ったりして。