如何使用尾递归在python中遍历目录树?

时间:2015-05-08 01:18:15

标签: python recursion tail-recursion

我正在开发一个只是一个超级基本命令行文件浏览器的项目。问题是我收到了Max recursion depth exceeded个错误。我想把它转换成至少有点尾递归的东西。这是代码:

import os, subprocess, itertools

def open_file(file, cwd):
    ''.join(file)
    if os.path.isdir(cwd + '/' + file) and '.app' not in file:
        os.chdir(cwd + '/' + file)
        print os.getcwd()
        filter_dir()
    elif '.app' in file:
        subprocess.call(['open', cwd + '/' + file])
    else:
        subprocess.call(['open', cwd + '/' + file])
        return

def input_checks(input, cwd):
    if input != '' and input != '../' and input[0] != '!' and input[0] != '.' and '<' not in input:
       out = itertools.ifilter(lambda x: input in x and '.' not in x, os.listdir(cwd))
    elif input == '../':
        print '../'
        cwd = os.chdir('../')
        filter_dir()
    elif input and input[0] == '!':
       out = itertools.ifilter(lambda x: input[1:] not in x, os.listdir(cwd))
    elif input and input[0] == '.':
       out = itertools.ifilter(lambda x: input[1:] in x, os.listdir(cwd))
    else:
       out = itertools.ifilter(lambda x: '.' not in x, os.listdir(cwd))
    return out

def filter_dir(input=''):
    cwd = os.getcwd()
    files = []
    out = input_checks(input, cwd)
    files = [i for i in out]
    for i in files:
        print i + '\t',
    for i in files:
        if i.lower() == input.lower():
            print i
            open_file(input, cwd)
            return
    if len(files) < 2:
        open_file(''.join(files), cwd)
        return
    print
    if '!' in input or '.' in input or '<' in input :
        input = ''
    print input,
    input = input + raw_input()
    print
    filter_dir(input)

我尝试了两种不同的解决方案[1] [2]。使用它们,函数运行一次然后停止。这可以在Python中进行尾递归吗?

[1] http://paulbutler.org/archives/tail-recursion-in-python/

[2] http://kylem.net/programming/tailcall.html

0 个答案:

没有答案