小编Joh*_*th0的帖子

为什么这个memoizer适用于递归函数?

我无法弄清楚为什么以下代码是以fib线性而非指数时间运行的.

def memoize(obj):
    """Memoization decorator from PythonDecoratorLibrary. Ignores
    **kwargs"""

    cache = obj.cache = {}

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwargs)
        return cache[args]
    return memoizer

@memoize
def fib(n):
    return n if n in (0, 1) else fib(n-1) + fib(n-2)
Run Code Online (Sandbox Code Playgroud)

例如,fib(100)并没有像我预期的那样完全爆炸.

我的理解是@memoize那套fib = memoize(fib).所以,当你打电话fib(100),看到100是不在缓存中,它会调用obj100.但这obj原始的fib功能,所以不应该花费同样长的时间(在第一次评估时),就好像我们根本没有记忆一样?

python recursion memoization

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

QMetaType和继承

好的,所以我对Qt和C++都不熟悉.我正在尝试将QMetaType与我自己的类一起使用,我无法让它与子类一起使用.这就是我所拥有的(可能有很多问题,抱歉):

testparent.h:

#include <QMetaType>

class TestParent
{
public:
    TestParent();
    ~TestParent();
    TestParent(const TestParent &t);
    virtual int getSomething(); // in testparent.cpp, just one line returning 42
    int getAnotherThing();      // in testparent.cpp, just one line returning 99
};

Q_DECLARE_METATYPE(TestParent)
Run Code Online (Sandbox Code Playgroud)

这是test1.h:

#include <QMetaType>
#include "testparent.h"

class Test1 : public TestParent
{
public:
    Test1();
    ~Test1();
    Test1(const Test1 &t);
    int getSomething();          // int test1.cpp, just one line returning 67
};

Q_DECLARE_METATYPE(Test1)
Run Code Online (Sandbox Code Playgroud)

...(除非另有说明,否则此处声明的所有成员都被定义为在testparent.cpp或test1.cpp中不执行任何操作(只需打开括号,右括号).这是main.cpp:

#include <QtGui/QApplication>
#include "test1.h"
#include "testparent.h"
#include <QDebug>

int main(int argc, char …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance qt introspection qt4

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

标签 统计

c++ ×1

inheritance ×1

introspection ×1

memoization ×1

python ×1

qt ×1

qt4 ×1

recursion ×1