简体   繁体   English

Python递归函数未返回值

[英]Python recursive function not returning value

This is my first question here so my sincerest apologies if I've written TOO much and thanks so much in advance for taking a look. 这是我的第一个问题,因此如果我写的太多了,我表示由衷的歉意,并非常感谢您提前查看。

PROBLEM: 问题:

I've written a function which should, if necessary, call itself x times and if unsuccessful return nothing. 我编写了一个函数,如果有必要,应该调用自身x次,如果失败,则不返回任何内容。 However, when the function seems to be successful, it still returns None. 但是,当函数看起来成功时,它仍然返回None。

BACKGROUND: I have a number of directories which represent months in the year 2009. Not all of the months exist though, therefore if this is the case, I want to get the previous month, check if a directory for that month exists, and if not continue going back one month AT MOST for 6 months. 背景:我有许多目录,代表2009年的月份。但是,并非所有月份都存在,因此,如果是这种情况,我想获取上个月,请检查该月份的目录是否存在,以及是否请不要在MOST的6个月后继续返回一个月。

Below you see the month 09 in the date_tag, which in my test case does not exist. 在下面,您会在date_tag中看到09月,在我的测试案例中,该月不存在。 Neither does 08 or 07. Thus the function SHOULD return 06 but instead it returns None. 08或07都不会。因此,该函数应返回06,但应返回None。

import pdb
import generate_months_module
import os

date_tag = '2000/2000/2009/09'
tree_location = '/Users/kelly/Documents/projects/komm/data/directory-tree/'

def iterateOverMonths(date_tag, x):
    if x <= 0:
        return_string = 'no dates found'
        return return_string
    else:
        new_date = generate_months_module.handleDateShifts(date_tag)[1]
        print '\tNEW DATE after calling handleDateShifts' + new_date
        full_path = tree_location + '/' + new_date
        if checkDirectoryExistance(full_path) == True:
            print '\t'+ full_path + ' is a real path'
            return full_path
        else:
            print 'dir does not exist'                                                                                                                       
            iterateOverMonths(new_date, x-1)

def checkDirectoryExistance(dir_path):
    "check if a directory exists, return true or false"
    if os.path.isdir(dir_path) == True:
        return True
    else:
        return False

print iterateOverMonths(date_tag, 6)

The generate_months_module.handleDateShifts is supposed to just get the previous month and return it. generate_months_module.handleDateShifts应该只获取上个月并返回。 (This works in other test cases so I highly doubt the problem is here!) (这在其他测试用例中也有效,因此我高度怀疑问题出在这里!)

My output from this then is: 那么我的输出是:

6
    NEW DATE after calling handleDateShifts2000/2000/2009/08
    dir does not exist
5
    NEW DATE after calling handleDateShifts2000/2000/2009/07
    dir does not exist
4
    NEW DATE after calling handleDateShifts2000/2000/2009/06

    /Users/kelly/Documents/projects/komm/data/directory-tree/2000/2000/2009/06 is a real path

    returning full path
    None

When I use pdb.set_trace() prior to "return full_path" it seems like the function is being called again DESPITE the IF clause being True and thus writing over the "full_path" variable I want to return. 当我在“ return full_path”之前使用pdb.set_trace()时,似乎该函数被再次调用,尽管IF子句为True,因此覆盖了我想返回的“ full_path”变量。

Why isn't the path "/Users/kelly/Documents/projects/komm/data/directory-tree/2000/2000/2009/06" being returned?? 为什么不返回路径“ / Users / kelly / Documents / projects / komm / data / directory-tree / 2000/2000/2009/06”?

imported function: 导入功能:

If one should be interested and want to re-create this the handleDateShifts function is as follows (my apologies, it's a bit messy): 如果您应该对此感兴趣并想要重新创建它,则handleDateShifts函数如下所示(我很抱歉,这有点混乱):

def handleDateShifts(corpus_date_string):
    "get background corpus date strings ALSO call this function if month does not exist and need to go back even further"
    century, decade, year, month = corpus_date_string.split('/')
    if month == '01' or month == '02':
        #handle date boundaries which can affect year, decade and cent                                                   
        background_mo_1 = '11'
        background_mo_2 = '12'
        millenium_shift = re.search('[1-9][0][0][0]$', year)
        century_shift = re.search('[1-9][0][0]$', year)
        decade_shift = re.search('[1-9][0]$',year)
        if century_shift or millenium_shift:
            century = int(year) - 100
            decade = int(year) - 10
            year = int(year) - 1
        elif decade_shift:
            decade = int(year) - 10
            year = int(year) - 1
        elif not decade_shift and not century_shift:
            year = int(year) - 1
        background_1_string = str(century) +'/'+ str(decade) +'/'+ str(year) +'/'+ str(background_mo_1)
        background_2_string = str(century) +'/'+ str(decade) +'/'+ str(year) +'/'+ str(background_mo_2)
    else: #the cent/dec/year can stay the same                                                                           
        background_mo_1 = int(month) - 2
    background_mo_2 = int(month) - 1
        if len(str(background_mo_1)) == 1:
            background_mo_1 = '0' + str(background_mo_1)
        if len(str(background_mo_2)) == 1:
            background_mo_2 = '0' + str(background_mo_2)
        background_1_string = str(century) +'/'+ str(decade) +'/'+ str(year) +'/'+ str(background_mo_1)
        background_2_string = str(century) +'/'+ str(decade) +'/'+ str(year)+'/'+ str(background_mo_2)
    return background_1_string, background_2_string

You don't return anything in this branch (your result is lost): 您在此分支中不返回任何内容(结果丢失):

    else:
        print 'dir does not exist'                                                                                                                       
        iterateOverMonths(new_date, x-1)

If function runs it course without explicit return <smth> , None is returned. 如果函数运行过程没有显式return <smth> ,则不return <smth> None值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM