优化我的循环python以提高速度

时间:2017-05-21 15:59:39

标签: loops python-3.5

我的功能是尝试在两个日期的列表中获取一系列年度字符串。

我已经工作了一段时间,并设法编写了一个非常糟糕的解决方案。我想帮助如何优化我的算法。

我最初的印象是用

来评估算法
while (beginMonth!=endMonth) and (beginYear!=endYear)

但是对于

的输入值,这被评估为false

beginYear = 2016和beginMonth = 10

endYear = 2017和endMonth = 02

返回

[" 201610"," 201611"," 201612"]

它比我预期的更早退出循环。

所以给出了输入 fromDate =" 201610" toDate =" 201702"

它应该返回 [" 201610"," 201611"," 201612"," 201701"," 201702"]

特别是我担心这个循环

效率低下的循环

while True:
    dateRange.append(str(beginYear) + str(beginMonth).zfill(2))
    if beginYear >= endYear:
        if beginMonth >= endMonth:
            break
    beginMonth = beginMonth + 1
    if (beginMonth > 12):
        beginMonth = 1
        beginYear = beginYear + 1
    print("inc {0}{1}".format(beginYear,str(beginMonth).zfill(2)))

完整代码

def getRange(fromDate, toDate):
    dateRange = []
    beginYear = int(fromDate[:4])
    beginMonth = int(fromDate[-2:])
    endYear = int(toDate[:4])
    endMonth = int(toDate[-2:])

    if endYear < beginYear:
        print("End year must be less than begin year")
        return
    elif endYear - beginYear > 25:
        print("Maximum number of years reached, can't analyse more than 25 
years")

    else:
        #iterate from current date one month at a time to end date
        while True:
            dateRange.append(str(beginYear) + str(beginMonth).zfill(2))
            if beginYear >= endYear:
                if beginMonth >= endMonth:
                    break
            beginMonth = beginMonth + 1
            if (beginMonth > 12):
                beginMonth = 1
                beginYear = beginYear + 1
            print("inc {0}{1}".format(beginYear,str(beginMonth).zfill(2)))
    return dateRange

0 个答案:

没有答案