1. 程式人生 > >Python - 按天算年齡

Python - 按天算年齡

python splay hide class 入門 forum color 出生日期 AR

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

舉例:你是昨天出生的,那麽輸出就為1

分三種情況討論:

1、年份和月份都相同

2、年份相同月份不同,先計算出生當天是當年的第幾天,後計算當前為當年的第幾天,相減

3、年份不同,還是先計算出生當天為當年的第幾天,後計算當前為當年的第幾天,做閏年判斷,逐一相加

閏年為一下兩種情況

1、能被400整除

2、能被4整除但不能被100整除

、、、、、、、、、、、、、、、

本題來自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

Python - 按天算年齡