나는 재귀 적으로 호출되는 함수가 있으며 재귀의 현재 수준을 알고 싶습니다. 아래의 코드는 내가 그것을 계산하는 데 사용하는 방법을 보여 주지만 예상 된 결과를 제공하지는 않습니다.파이썬에서 재귀 호출 수준 찾기
예. : 내가 부를 것이다, 내 디렉토리 구조에서 :
디렉토리 구조는 디렉토리를 재귀 수준을 인쇄, 디렉토리 경로 감안할 때 :
import os
funccount = 0
def reccount(src):
global funccount
print "Function level of %s is %d" %(src, funccount)
def runrec(src):
global funccount
funccount = funccount + 1
lists = os.listdir(src)
if((len(lists) == 0)):
funccount = funccount - 1
reccount(src)
for x in lists:
srcname = os.path.join(src, x)
if((len(lists) - 1) == lists.index(x)):
if (not(os.path.isdir(srcname))):
funccount = funccount - 1
if os.path.isdir(srcname):
runrec(srcname)
runrec(C:\test)
문제 : 시스템 경로에 대한 재귀 수준을 찾으려면 함수 "reccount (Test)"(함수는 MainFolder의 경로와 함께 호출됩니다). 각 폴더에 대한 재귀 호출 수준을 알고 싶습니다. (디렉토리에만 해당)
Test:
|----------doc
|----------share
|----------doc
|----------file1
|----------bin
|----------common
|----------doc
|----------extras
|----------file2
내가 프로 시저를 호출하면, 다음과 같은 결과를 얻을 : 당신이 볼 수 있듯이
Function level of C:\test is 1
Function level of C:\test\bin is 2
Function level of C:\test\bin\common is 3
Function level of C:\test\bin\common\doc is 3
Function level of C:\test\doc is 3
Function level of C:\test\extras is 3
Function level of C:\test\share is 4
Function level of C:\test\share\doc is 5
, 그것은 빈/일반/문서에 대한 결과를 출력 할 때, 그것은 3을 대신 출력을 4 및 이후의 모든 결과가 잘못되었습니다.
왜 부정적 수 :
그런 식으로, 당신은 전역 변수가 필요하지 않습니다? – sarbjit