Sunday 22 July 2012

date.py

午前中に たけいさん が話にださはったのでふと思いついて,
(日付,月,年) (日付と年は integer, 月 は int または "Jan" , "Feb" など三文字略記の str)
を引数として,年初から数えて何番目かを返すプログラム(というほどのものでもないけど).
範囲外のものや型の違うのを入れようとすると i, 2i, 3i という虚数を返すようにしてみた
(ぴゅとん の表記で言うと 1j, 2j, 3j ということになる).
年(エラーなら 3i が返る)→月(2i)→日(i) の順にチェックするので,
全部予定外のものを入れるととりあえず年がエラーといって返してきます.
閏年とかも対応(副産物として ifleapyear : 閏年かどうかを返す関数).

ぐるぐるに上げてみる けどこれ .py ではプレビューしてくれないようなので
一応下に貼ってみましょうか.



#
#
# ********** Mutsuteru : twitter @exumbra_insolem all rights reserved.
#
#
#
#name of the month (string) to number
months = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12)
#days in each month.
daysinmonths = [31,28,31,30,31,30,31,31,30,31,30,31]
#days in a year.
daysinayear = 365
#checks leap year.
def ifleapyear(year):
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        return True
    else:
        return False
#returns the nombre of the date.
# ERRORS ARE FOLLOWING::::::::
#  1j : day does not have a proper value
#  2j : month does not have a proper value:
#        month has to be i)  integer between 1 and 12 or
#                ii) Jan ~ Dec .
#  3j : year is not a positive integer

def datecount(day,month,year):
#First We have to check the day, month, year have proper values.
    if not (type(year) is int and year > 0 ):
        return 3j
    if ifleapyear(year):
        daysinayear = 366
        daysinmonths[1] = 29
    if type(month) is int and 1 <= month <= 12:
        pass
    elif type(month) is str and month in months:
        month = months[month]
    else:
        return 2j
    if not (type(day) is int and 1<= day <= daysinmonths[month-1]):
        return 1j
    datenum = 0
    for i in range(month - 1):
        datenum += daysinmonths[i]
    datenum += day
    return datenum

No comments:

Post a Comment