2015-04-04 74 views
0

我試圖解決在Udacity的CS-101當然,這可選問題 - 它要求兩個日期間計算天數。我的代碼適用於所有測試用例,但由於某種原因,它不適用於案例1(2012年1月1日 - 2012年2月28日),但它返回56,但實際答案是58.我無法用頭圍繞那,任何建議將不勝感激。日之間的日期(Python)的

def leap_year(year): 
    if year % 4 != 0: 
     return "Common Year" 
    elif year % 100 != 0: 
     return "Leap Year" 
    elif year % 400 != 0: 
     return "Common Year" 
    else: 
     return "Leap Year" 

def days_in_month(month): 
    months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 
    i = 0 
    days = 0 
    while i <= month: 
     days += months[i- 1] 
     i += 1 
    return days 


def daysBetweenDates(year1, month1, day1, year2, month2, day2): 
    i = year1 
    leap_count = 0 
    while i <= year2: 
     if leap_year(i) == "Leap Year": 
      leap_count += 1 
     i += 1 
    return ((year2 - year1) * 365 + (days_in_month(month2) - days_in_month(month1)) + (day2 - day1)) + leap_count 

# 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() 
+0

不知道如果你被允許使用datetime模塊,但它可能是爲'ABS這麼簡單((日期(2012年1,1) - 日期(2012,2,28)) .days)' – Andrew 2015-04-04 05:24:41

+0

@AndrewFarber嘿,謝謝你,但我想解決它沒有任何內置功能,只是想了解實際的算法。 – hky404 2015-04-04 05:25:46

+0

我從未理解這種情緒。 「這是你的解決方案。」 「不,我不想要解決方案,我想重新發明輪子!」 :P – 2015-04-04 05:38:14

回答

4

,我們在您daysBetweenDates函數體的幾個問題 - 曆法計算是非常困難,所以我讚揚你想他們,但是,男人!你是在痛苦的世界(相當與Python無關 - 都是關於我們日曆的瘋狂程度!)。

舉個例子,只是你最終return ED表達:

((year2 - year1) * 365 + (days_in_month(month2) - days_in_month(month1)) + (day2 - day1)) + leap_count 

你爲什麼會增加leap_count(以前計算的YEAR1和YEAR2之間的閏年數包括在內)無條件?!想想看。獲得一個優勢案例來簡化你的推理。假設year1和year2是相同的,並且同樣爲month1和month2。現在leap_count將是1,如果今年是bisextile,否則爲0 - 和爲什麼可以在一年的性質可能在所有事來計算,例如,1月1日和1月9日或5月1日之間的天9?

然而,通過公式你使這件事慎之又慎 - 所以你會聲稱這些差異不是等於2012(bisextile)與2013(不bisextile),您知道是錯誤的。

這就是你有可能落入曆法計算的花樣繁多的只是一個例子,唉!

我認爲你需要一個完全不同的算法。我懷疑區分開始日期和結束日期是否在同一年是最簡單的。如果是的話,那麼只有在二月份在兩個日期之間時,你纔會關心閏年。如果不是,則計算中間年份的天數確實需要檢查閏年(大致與現在一樣)。無論哪種方式,輔助功能,如「天自年初」和/或「天至年底」是你的朋友...... - - !)

+0

這是有益的亞歷克斯。只是不明白,爲什麼有人投票我的帖子(對stackoverflow非常仇恨)哈哈 – hky404 2015-04-04 08:03:29

2

對於任何人後來來尋找如何做到這一點的普通的Python的方式,你應該做的:

import datetime 

def delta_days(year1, month1, day1, year2, month2, day2): 
    return abs(datetime.date(year1, month1, day1) - \ 
       datetime.date(year2, month2, day2)).days