开发者

Recursion counter solution in python

The basic idea of the program is that it searches a large list for a given string, notes its index, and assigns other words based upon that index. The major开发者_如何学JAVA issue is that, as there are some requirements built into the system that reject certain words, a very large recursion depth is likely to occur. There may be solutions that circumvent this problem (which I would be very interested in seeing) by avoiding recursion altogether, but recursion seems to be the most elegant solution, especially as there will be several versions of this program, that handle more and more words and indexes. Therefore, the major question is, how is it possible to get it to count recursion, so that it can kick out of the function if a depth limit is reached? Ideally, this would be in a loop, so that it could start where it left off from after that, but that seems to be a different problem. As it is, the counters are resetting unexpectedly.

lines = open ('newkj')
corpus= []
for line in lines :
corpus.extend(line.split())

limit = 800000
globallimit=800000
count=0
count2=0

"""This one is unique as it carries the null case in it. It is also a forward facing no check function"""

def curgb (indexa=indexof('the'),count=0) :
    worda=wordfor (indexa)
    wordb = wordfor (indexa+1)
    indexb=indexof(wordb)
    wordc = wordfor (advance(indexa)+1)
    indexc=indexof (wordc)
    if indexa> globallimit:
        print ('no results')
        return (indexa)
    elif indexb<limit and indexc<limit:
        curgd (indexc,indexb,indexa,count2+1)
    else:
        curgb(advance(indexa),count+1)
"""This function is also forward facing no check"""

def curgd (indexc,indexb,indexa,count2=0):
    wordd = wordfor (indexc+1)
    indexd = indexof(wordd)
    indexd=check(indexd,indexb,-1)
    print(count2)
    if indexd<limit and indexc<limit and indexb< limit and wordfor(indexd-1)==wordfor(indexb):
        """print (wordfor(indexa),wordfor(indexb))
        print (wordfor(indexd),wordfor (indexc))
        print ('     ')"""
        curgd(advance(indexc),indexb,indexa,count2+1)
    else :
        curgb(advance(indexa),count+1)

As it is, this is simplified and not likely to hit a recursion limit, but the major problem of the counter resetting is still there. Running the program is a matter of calling curgb() with an integer argument, corresponding to a given index.


You seem to be mixing local and global variables.

In curgb, count2 variable isn't defined, and in curgd, count variable isn't defined. Either use global keywork to access them, or pass both variable as arguments to both functions (the later is what you should do)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜