Python 中递归计数器的解决方案
这个程序的基本思路是,它会在一个很大的列表中查找一个给定的字符串,找到后记录下它的位置(也就是索引),然后根据这个索引来分配其他的单词。主要的问题是,由于系统里有一些限制,导致某些单词会被拒绝,这样就可能会出现很深的递归调用。虽然可能有一些方法可以绕过这个问题(我很想看看这些方法),但递归似乎是最优雅的解决方案,尤其是这个程序会有多个版本,处理越来越多的单词和索引。因此,主要的问题是,怎么让程序能够计算递归的深度,以便在达到限制时能够退出这个函数?理想情况下,这应该是在一个循环中进行,这样可以在退出后从上次的位置继续,但这似乎是另一个问题。目前,计数器会意外地重置。
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)
现在这个程序是简化过的,不太可能达到递归限制,但计数器重置的问题依然存在。运行这个程序就是调用curgb()函数,并传入一个整数参数,这个参数对应于某个特定的索引。
1 个回答
1
你似乎把局部变量和全局变量搞混了。
在 curgb
这个函数里,count2
这个变量没有定义,而在 curgd
这个函数里,count
这个变量也没有定义。你可以用 global
这个关键词来访问它们,或者把这两个变量作为参数传给这两个函数(后者是你应该做的)。