【问题标题】:Recursion counter solution in pythonpython中的递归计数器解决方案
【发布时间】:2011-06-20 16:01:22
【问题描述】:

该程序的基本思想是它在一个大列表中搜索给定的字符串,记下它的索引,并根据该索引分配其他单词。主要问题是,由于系统中内置了一些拒绝某些单词的要求,因此可能会出现非常大的递归深度。可能有一些解决方案可以通过完全避免递归来规避这个问题(我很想看看),但递归似乎是最优雅的解决方案,特别是因为这个程序会有多个版本,可以处理越来越多的单词和索引。因此,主要问题是,如何让它计算递归,以便在达到深度限制时退出函数?理想情况下,这将是一个循环,以便它可以在那之后从中断的地方开始,但这似乎是一个不同的问题。事实上,计数器正在意外重置。

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() 并带有一个整数参数,对应于给定的索引。

【问题讨论】:

  • """docstrings""" 不是# comments。并且文档字符串必须是功能块内的第一行。
  • 这个问题缺乏特异性。应该将其移至代码审查网站。
  • @Apalala: Code Review 用于已经工作的代码。

标签: python recursion counter


【解决方案1】:

您似乎混合了局部变量和全局变量。

curgbcount2 变量未定义,curgdcount 变量未定义。要么使用global 键来访问它们,要么将两个变量作为参数传递给两个函数(后者是你应该做的)

【讨论】:

  • 我感觉这是全球/本地的区别。非常感谢您的帮助。
  • @MichaelRauh:如果对您有帮助,请不要忘记将此答案标记为已接受,如果您有任何问题,请参阅faq...谢谢!
  • 我试图立即,但它说我必须等待。现在已经完成了。
猜你喜欢
  • 2021-11-03
  • 1970-01-01
  • 2013-07-22
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多