Python - 按天算年齡

問題:輸入出生日期和當前的日期,輸出活了多少天ide

舉例:你是昨天出生的,那麼輸出就爲1函數

分三種狀況討論:spa

一、年份和月份都相同調試

二、年份相同月份不一樣,先計算出生當天是當年的第幾天,後計算當前爲當年的第幾天,相減code

三、年份不一樣,仍是先計算出生當天爲當年的第幾天,後計算當前爲當年的第幾天,作閏年判斷,逐一相加blog

閏年爲一下兩種狀況ci

一、能被400整除開發

二、能被4整除但不能被100整除it

 

、、、、、、、、、、、、、、、入門

 

本題來自Udacity的計算機科學導論課程,用來作Python入門

Python語言兼具通常高級語言和腳本語言的特色,在官網下了一個東東,只會作腳本,函數如今只會一行一行往裏敲,而後運行,沒法調試,好像是須要找一個開發環境,有空弄

附代碼

# By Websten from forums
#
# Given your birthday and the current date, calculate your age in days. 
# Account for leap days. 
#
# Assume that the birthday and current date are correct dates (and no 
# time travel). 
#


def is_leap(year):
    result = False
    if year % 400 == 0:
        result = True
    if year % 4 == 0 and year % 100 != 0:
        result = True
    return result

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if year1 == year2 and month1 == month2:
        days = day2 - day1
    if year1 == year2:
        days1 = 0
        i = 0
        while i < month1 - 1:
            days1 = days1 + daysOfMonths[i]
            i = i + 1
        days1 = days1 + day1
        if is_leap(year1) and month1 > 2:
            days1 = days1 + 1
        days2 = 0
        i = 0
        while i < month2 - 1:
            days2 = days2 + daysOfMonths[i]
            i = i + 1
        days2 = days2 + day2
        if is_leap(year2) and month2 > 2:
            days2 = days2 + 1
        days = days2 - days1
    else:
        days1 = 0
        i = 0
        while i < month1 - 1:
            days1 = days1 + daysOfMonths[i]
            i = i + 1
        days1 = days1 + day1
        if is_leap(year1) and month1 > 2:
            days1 = days1 + 1
        days2 = 0
        i = 0
        while i < month2 - 1:
            days2 = days2 + daysOfMonths[i]
            i = i + 1
        days2 = days2 + day2
        if is_leap(year2) and month2 > 2:
            days2 = days2 + 1
        days = 365 - days1 + days2
        if is_leap(year1):
            days = days + 1
        year1 = year1 + 1
        while year1 < year2:
            days = days + 365
            year1 = year1 + 1
            if is_leap(year1):
                days = days + 1
    return days
        
        
        


# Test routine

def test():
    test_cases = [((2012,1,1,2012,2,28), 58), 
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585 ),
                  ((1900,1,1,1999,12,31), 36523)]
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"

test()
View Code
相關文章
相關標籤/搜索