标签: recursion

递归的真实例子

什么是现实世界的问题,其中一个递归的方法是除了深度优先搜索(DFS)的自然的解决方案?

(我不考虑河内塔,斐波纳契数或因子现实世界的问题.在我看来,它们有点做作.)

recursion

86
推荐指数
15
解决办法
10万
查看次数

继承和递归

假设我们有以下类:

class A {

    void recursive(int i) {
        System.out.println("A.recursive(" + i + ")");
        if (i > 0) {
            recursive(i - 1);
        }
    }

}

class B extends A {

    void recursive(int i) {
        System.out.println("B.recursive(" + i + ")");
        super.recursive(i + 1);
    }

}
Run Code Online (Sandbox Code Playgroud)

现在让我们recursive在A班打电话:

public class Demo {

    public static void main(String[] args) {
        A a = new A();
        a.recursive(10);
    }

}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,输出从10减少.

A.recursive(10)
A.recursive(9)
A.recursive(8)
A.recursive(7)
A.recursive(6)
A.recursive(5)
A.recursive(4)
A.recursive(3)
A.recursive(2)
A.recursive(1)
A.recursive(0)
Run Code Online (Sandbox Code Playgroud)

让我们来看看令人困惑的部分.现在我们打电话给recursiveB班.

预期 …

java recursion inheritance

84
推荐指数
6
解决办法
4391
查看次数

假人的递归方案?

我正在寻找一些非常简单,易于掌握的递归方案和核心运动方案(catamorphisms,anorporphisms,hylomorphisms等)的解释,这些解释不需要跟随大量的链接,或者打开类别理论教科书.我确信我已经无意识地重新设计了许多这些方案,并在编码过程中将它们"应用"在我的头脑中(我相信我们很多人都有),但我不知道(共同)递归方案我是什么使用被称为.(好吧,我撒了谎.我刚刚读了一些这些,这引发了这个问题.但在今天之前,我一无所知.)

我认为这些概念在编程社区中的传播受到了令人生畏的解释和例子的阻碍 - 例如在维基百科上,而且在其他地方.

它们的名字也可能受到阻碍.我认为有一些替代的,较少的数学名称(关于香蕉和带刺铁丝网的东西?)但是我不知道我使用的递归方案的名称是什么.

我认为使用表示简单实际问题的数据类型的示例,而不是抽象数据类型(如二叉树)会有所帮助.

recursion haskell functional-programming recursion-schemes

82
推荐指数
3
解决办法
6815
查看次数

lambda函数可以递归吗?

可能重复:
c ++ 0x中的递归lambda函数

这是一个普通的旧递归函数:

int fak(int n)
{
    return (n <= 1) ? 1 : n * fak(n - 1);
}
Run Code Online (Sandbox Code Playgroud)

我如何编写像lambda函数这样的递归函数?

[](int n) { return (n <= 1) ? 1 : n * operator()(n - 1); }
// error: operator() not defined

[](int n) { return (n <= 1) ? 1 : n * (*this)(n - 1); }
// error: this wasn't captured for this lambda function
Run Code Online (Sandbox Code Playgroud)

是否有任何表达当前lambda的表达式,因此它可以递归调用自身?

c++ recursion lambda c++11

82
推荐指数
1
解决办法
3万
查看次数

Python:超出了最大递归深度

我有以下递归代码,在每个节点我调用sql查询以获取属于父节点的节点.

这是错误:

Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879768c>> ignored

RuntimeError: maximum recursion depth exceeded while calling a Python object
Exception AttributeError: "'DictCursor' object has no attribute 'connection'" in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879776c>> ignored
Run Code Online (Sandbox Code Playgroud)

我调用以获取sql结果的方法:

def returnCategoryQuery(query, variables={}):
    cursor = db.cursor(cursors.DictCursor);
    catResults = [];
    try:
        cursor.execute(query, variables);
        for categoryRow in cursor.fetchall():
            catResults.append(categoryRow['cl_to']);
        return catResults;
    except Exception, e:
        traceback.print_exc();
Run Code Online (Sandbox Code Playgroud)

我实际上对上述方法没有任何问题,但我还是把它放在了正确的问题概述上.

递归代码:

def leaves(first, path=[]):
    if first:
        for elem in …
Run Code Online (Sandbox Code Playgroud)

python recursion max tree-traversal depth

79
推荐指数
1
解决办法
17万
查看次数

为什么 Python 递归如此昂贵,我们能做些什么?

假设我们要计算一些斐波那契数,以 997 为模。

因为n=500在 C++ 中我们可以运行

#include <iostream>
#include <array>

std::array<int, 2> fib(unsigned n) {
    if (!n)
        return {1, 1};
    auto x = fib(n - 1);
    return {(x[0] + x[1]) % 997, (x[0] + 2 * x[1]) % 997};
}

int main() {
    std::cout << fib(500)[0];
}
Run Code Online (Sandbox Code Playgroud)

在 Python 中

def fib(n):
    if n==1:
        return (1, 2)
    x=fib(n-1)
    return ((x[0]+x[1]) % 997, (x[0]+2*x[1]) % 997)

if __name__=='__main__':
    print(fib(500)[0])
Run Code Online (Sandbox Code Playgroud)

两者都可以毫无问题地找到答案 996。我们采用模数来保持合理的输出大小,并使用对来避免指数分支。

对于n=5000,C++ 代码输出 783,但 Python 会抱怨

RecursionError: …
Run Code Online (Sandbox Code Playgroud)

c++ python stack-overflow recursion

79
推荐指数
6
解决办法
1万
查看次数

递归函数从数据库结果生成多维数组

我正在寻找一个函数,它接受一个页面/类别数组(来自平面数据库结果),并根据父ID生成一个嵌套页面/类别项的数组.我想以递归方式执行此操作,以便可以完成任何级别的嵌套.

例如:我在一个查询中获取所有页面,这就是数据库表的样子

+-------+---------------+---------------------------+
|   id  |   parent_id   |           title           |
+-------+---------------+---------------------------+
|   1   |       0       |   Parent Page             |
|   2   |       1       |   Sub Page                |
|   3   |       2       |   Sub Sub Page            |
|   4   |       0       |   Another Parent Page     |
+-------+---------------+---------------------------+
Run Code Online (Sandbox Code Playgroud)

这是我想在我的视图文件中处理的数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
            [title] => Parent Page
            [children] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 2
                                    [parent_id] => 1
                                    [title] => Sub …
Run Code Online (Sandbox Code Playgroud)

php arrays recursion function

74
推荐指数
2
解决办法
6万
查看次数

使用foldr编写foldl

在Real World Haskell中,第4章.函数式编程

用foldr写foldl:

-- file: ch04/Fold.hs
myFoldl :: (a -> b -> a) -> a -> [b] -> a

myFoldl f z xs = foldr step id xs z
    where step x g a = g (f a x)
Run Code Online (Sandbox Code Playgroud)

上面的代码让我很困惑,有人打电话给dps用一个有意义的名字重写它,使它更清晰:

myFoldl stepL zeroL xs = (foldr stepR id xs) zeroL
where stepR lastL accR accInitL = accR (stepL accInitL lastL)
Run Code Online (Sandbox Code Playgroud)

其他人,Jef G,通过提供一个例子并逐步展示基础机制,做得非常出色:

myFoldl (+) 0 [1, 2, 3]
= (foldR step id [1, 2, …
Run Code Online (Sandbox Code Playgroud)

recursion haskell fold

73
推荐指数
4
解决办法
1万
查看次数

外行人的术语是使用PHP的递归函数

任何人都可以用PHP(不使用Fibonacci)在外行语言和使用示例中向我解释一个递归函数吗?我正在看一个例子,但斐波那契完全失去了我!

提前谢谢;-)您还经常在Web开发中使用它们吗?

php recursion function

72
推荐指数
6
解决办法
11万
查看次数

递归ConcurrentHashMap.computeIfAbsent()调用永远不会终止.错误或"功能"?

前段时间,我发表了一篇关于递归计算斐波纳契数的Java 8函数式方法的博文,其中包含一个ConcurrentHashMap缓存和新的有用computeIfAbsent()方法:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {
    static Map<Integer, Integer> cache = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        System.out.println(
            "f(" + 8 + ") = " + fibonacci(8));
    }

    static int fibonacci(int i) {
        if (i == 0)
            return i;

        if (i == 1)
            return 1;

        return cache.computeIfAbsent(i, (key) -> {
            System.out.println(
                "Slow calculation of " + key);

            return fibonacci(i - 2) + fibonacci(i - 1);
        });
    }
} …
Run Code Online (Sandbox Code Playgroud)

java recursion concurrenthashmap java-8

71
推荐指数
2
解决办法
6258
查看次数