GVKun编程网logo

为什么Python具有最大的递归深度?(为什么python具有最大的递归深度数据)

4

本文将介绍为什么Python具有最大的递归深度?的详细情况,特别是关于为什么python具有最大的递归深度数据的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉

本文将介绍为什么Python具有最大的递归深度?的详细情况,特别是关于为什么python具有最大的递归深度数据的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于C++ 函数的递归实现:递归深度有限制吗?、Python Tkinter:RecursionError:超过最大递归深度、python – json树中超出了最大递归深度、python – 为什么这个pickle在没有递归的情况下达到最大递归深度?的知识。

本文目录一览:

为什么Python具有最大的递归深度?(为什么python具有最大的递归深度数据)

为什么Python具有最大的递归深度?(为什么python具有最大的递归深度数据)

Python具有最大的递归深度,但没有最大的迭代深度。为什么限制递归?像迭代一样对待递归而不限制递归调用的数量会更自然吗?

让我只说这个问题的根源在于尝试实现流。例如,假设我们要编写一个流以产生自然数:

def stream_accum(s,n): # force the stream to a list of length n
    def loop(s,acc):
        if len(acc) == n:
            return acc
        hd,tl = s()
        return loop(tl,acc + [hd])
    return loop(s,[])


def nats():
    def loop(n):
        return n,lambda: loop(n+1)
    return loop(1)

流的递归定义非常吸引人。但是,我想更好/更多的pythonic方法是使用生成器。

C++ 函数的递归实现:递归深度有限制吗?

C++ 函数的递归实现:递归深度有限制吗?

c++++ 函数的递归深度受到限制,超过该限制会导致栈溢出错误。限制值因系统和编译器而异,通常在 1000 到 10000 之间。解决方法包括:1. 尾递归优化;2. 尾调用;3. 迭代实现。

C++ 函数的递归实现:递归深度有限制吗?

C++ 函数的递归实现:递归深度有限制吗?

在 C++ 中,递归是一种强大的技术,它允许函数调用自身。然而,递归深度是有限制的,超过此限制会引发一个称为栈溢出的错误。

栈溢出

每个函数调用都会将一些数据(例如函数参数、局部变量和返回地址)推到栈上。当函数返回时,这些数据会被弹出栈。如果递归深度太大,栈可能会耗尽,导致栈溢出错误。

立即学习“C++免费学习笔记(深入)”;

递归深度限制

C++ 未定义递归深度限制的具体值,因为它取决于系统和编译器。然而,通常可以将限制视为 1000 到 10000 之间。

实战案例

考虑以下递归函数来计算斐波那契数列的第 n 项:

int fib(int n) {
  if (n <= 1)
    return n;
  else
    return fib(n - 1) + fib(n - 2);
}
登录后复制

如果尝试计算 fib(10000),它将导致栈溢出,因为递归深度超过了限制。

解决方法

有几种解决方法可以解决递归深度限制问题:

  • 尾递归优化:某些编译器可以优化尾递归调用,将它们转换为迭代,从而消除对递归栈的需求。
  • 尾调用:手动将递归调用转换为尾调用,在函数返回之前对其进行参数和返回值的赋值。
  • 迭代实现:重写函数以使用循环而不是递归来计算结果。

结论

C++ 函数的递归深度是有限制的,超过此限制会导致栈溢出错误。通过尾递归优化、尾调用或迭代实现,可以解决此限制。

以上就是C++ 函数的递归实现:递归深度有限制吗?的详细内容,更多请关注php中文网其它相关文章!

Python Tkinter:RecursionError:超过最大递归深度

Python Tkinter:RecursionError:超过最大递归深度

如果从SlideshowModel(tk.Tk,tk.Frame)类中删除“ tk.Tk”和“ tk.Frame”会发生什么?另外,您也应该将self.grid_height替换为self.grid_h(第22行)。

python – json树中超出了最大递归深度

python – json树中超出了最大递归深度

def get_children(node):
    for child in node['children']:
        yield child 
        for grandchild in get_children(child):
            yield grandchild


for line in f:
    d = json.loads(line)
    child_dic={}
    for child in get_children(d):
        if child not in child_dic.keys():
            child_dic[child["id"]]=1

当我用他的代码来查找json树有的孩子数时,
我收到一个错误
调用Python对象时超出了最大递归深度.
请帮我一样.

解决方法

你有一棵树的深度超过了998级:

>>> def build_nested(depth):
...     d = {'children': []}
...     for i in range(depth - 1):
...         d['children'].append({'children': []})
...         d = d['children'][0]
...     return d
... 
>>> try:
...     len(list(get_children(build_nested(998))))
... except RuntimeError:
...     print 'too deep'
... 
997
>>> try:
...     len(list(get_children(build_nested(999))))
... except RuntimeError:
...     print 'too deep'
... 
too deep

在这种情况下不要使用递归.使用堆栈:

def get_children(node):
    stack = [node]
    while stack:
        node = stack.pop()
        stack.extend(node['children'][::-1])
        yield node

这个简单的方法首先遍历您的树深度,就像递归版本一样,以相同的顺序遍历.

这仅受您可以为Python提供的内存量的限制:

>>> try:
...     len(list(get_children(build_nested(999))))
... except RuntimeError:
...     print 'too deep'
... 
998
>>> try:
...     len(list(get_children(build_nested(10**6))))
... except RuntimeError:
...     print 'too deep'
... 
999999

然而,这无助于加载这样的物体; json库也有限制:

>>> import json
>>> json.loads('{"a":' * 100000 + '1' + '}' * 100000)
Traceback (most recent call last):
   File "<stdin>",line 1,in <module>
   File "/.../lib/python2.7/json/__init__.py",line 338,in loads
     return _default_decoder.decode(s)
   File "/.../lib/python2.7/json/decoder.py",line 366,in decode
     obj,end = self.raw_decode(s,idx=_w(s,0).end())
   File "/.../lib/python2.7/json/decoder.py",line 382,in raw_decode
     obj,end = self.scan_once(s,idx)
RuntimeError: maximum recursion depth exceeded while calling a Python object

您可以尝试使用sys.setrecursionlimit()提高Python递归限制,但要小心.将它设置得太高,你将使用段错误来破坏Python解释器.首先查看sys.getrecursionlimit()并将其作为起点来增加限制,直到您可以加载数据.

我不知道任何其他Python JSON库可以处理您看起来具有如此深度的JSON对象. jsonlib2只是段错误,ujson有1024个对象的硬编码深度限制,而且demjson也给你一个最大的递归深度错误.

python – 为什么这个pickle在没有递归的情况下达到最大递归深度?

python – 为什么这个pickle在没有递归的情况下达到最大递归深度?

这是我的代码,它不包含递归,但它在第一个pickle上达到最大递归深度…

码:

#!/usr/bin/env python
from bs4 import BeautifulSoup
from urllib2 import urlopen
import pickle

# open page and return soup list
def get_page_startups(page_url):
  html = urlopen(page_url).read()
  soup = BeautifulSoup(html,"lxml")
  return soup.find_all("div","startup item")

#
# Get certain text from startup soup
#
def get_name(startup):
  return startup.find("a","profile").string
def get_website(startup):
  return startup.find("a","visit")["href"]
def get_status(startup):
  return startup.find("p","status").strong.string[8:]
def get_twitter(startup):
  return startup.find("a","comment").string
def get_high_concept_pitch(startup):
  return startup.find("div","headline").find_all("em")[1].string
def get_elevator_pitch(startup):
  startup_soup = BeautifulSoup(urlopen("http://startupli.st" + startup.find("a","profile")["href"]).read(),"lxml")
  return startup_soup.find("p","desc").string.rstrip().lstrip()
def get_tags(startup):
  return startup.find("p","tags").string
def get_blog(startup):
  try:
    return startup.find("a","visit blog")["href"]
  except TypeError:
    return None
def get_facebook(startup):
  try:
    return startup.find("a","visit facebook")["href"]
  except TypeError:
    return None
def get_angellist(startup):
  try:
    return startup.find("a","visit angellist")["href"]
  except TypeError:
    return None
def get_linkedin(startup):
  try:
    return startup.find("a","visit linkedin")["href"]
  except TypeError:
    return None
def get_crunchbase(startup):
  try:
    return startup.find("a","visit crunchbase")["href"]
  except TypeError:
    return None


# site to scrape
BASE_URL = "http://startupli.st/startups/latest/"

# scrape all pages
for page_no in xrange(1,142):
  startups = get_page_startups(BASE_URL + str(page_no))

  # search soup and pickle data
  for i,startup in enumerate(startups):
    s = {}
    s[''name''] = get_name(startup)
    s[''website''] = get_website(startup)
    s[''status''] = get_status(startup)
    s[''high_concept_pitch''] = get_high_concept_pitch(startup)
    s[''elevator_pitch''] = get_elevator_pitch(startup)
    s[''tags''] = get_tags(startup)
    s[''twitter''] = get_twitter(startup)
    s[''facebook''] = get_facebook(startup)
    s[''blog''] = get_blog(startup)
    s[''angellist''] = get_angellist(startup)
    s[''linkedin''] = get_linkedin(startup)
    s[''crunchbase''] = get_crunchbase(startup)

    f = open(str(i)+".pkl","wb")
    pickle.dump(s,f)
    f.close()

  print "Done " + str(page_no)

这是引发异常后的0.pkl的内容:

http://pastebin.com/DVS1GKzz千行长!

在泡菜中有一些来自BASE_URL的HTML ……但是我没有腌制任何html字符串……

解决方法

BeautifulSoup .string属性实际上不是字符串:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(''<div>Foo</div>'')
>>> soup.find(''div'').string
    u''Foo''
>>> type(soup.find(''div'').string)
    bs4.element.NavigableString

尝试使用str(soup.find(‘div’).string),看看它是否有帮助.另外,我不认为Pickle真的是这里最好的格式.在这种情况下,JSON更容易.

今天的关于为什么Python具有最大的递归深度?为什么python具有最大的递归深度数据的分享已经结束,谢谢您的关注,如果想了解更多关于C++ 函数的递归实现:递归深度有限制吗?、Python Tkinter:RecursionError:超过最大递归深度、python – json树中超出了最大递归深度、python – 为什么这个pickle在没有递归的情况下达到最大递归深度?的相关知识,请在本站进行查询。

本文标签: