python小题 按天算年龄

2020-06-27  本文已影响0人  生活就是爱

今天玩了一个题目,本来以为很简单,结果也折腾了好久,还在网上搜了一下解题思路才把代码写出来

一、题目

问题:输入出生日期和当前的日期,输出活了多少天

举例:你是昨天出生的,那么输出就为1

本题来自Udacity的计算机科学导论课程,用来做Python入门
官网还有几个测试用例

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)]

二、解题思路

分三种情况讨论:

1、年份和月份都相同

2、年份相同月份不同,先计算出生当天是当年的第几天,后计算当前为当年的第几天,相减

3、年份不同,还是先计算出生当天为当年的第几天,后计算当前为当年的第几天,做闰年判断,逐一相加

闰年为一下两种情况

1、能被400整除

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

三、代码实现

# 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_runnian(year):
    if year%400 == 0:
        return True
    elif year%4==0 and year%100!=0:
        return True
    else:
        return False
        
def days_of_year(year):
    if not is_runnian(year):
        days_of_year = 365
    else:
        days_of_year = 366
    return days_of_year
    
def count_day(year,month,day):
    if not is_runnian(year):
        daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    else:
        daysOfMonths = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    days = 0
    for i in range(1,month):
        days += daysOfMonths[i-1]
    days+=day
    return days

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    ##
    # Your code here.
    ##
    if year1==year2 and month1==month2:
        return day2-day1
    elif year1==year2:
        return count_day(year2,month2,day2)-count_day(year1,month1,day1)
    else:
        if (year2-year1)==1:
            return days_of_year(year1)-count_day(year1,month1,day1)+count_day(year2,month2,day2)
        else:
            days=0
            for i in range(year1+1,year2):
                days+=days_of_year(i)
            days = days+days_of_year(year1)-count_day(year1,month1,day1)+count_day(year2,month2,day2)
            
        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",result
        else:
            print "Test case passed!", args

test()

参考资料:
python 按天算年龄

上一篇 下一篇

猜你喜欢

热点阅读