本文介绍了使用记忆来计算加泰罗尼亚语数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正打算使用记忆来计算加泰罗尼亚语数字,但似乎不起作用,我需要更改什么?

def catalan_mem(n, memo = None):
    if n==0:
        return 1
    if memo == None:
        memo = {}
    b=0
    if n not in memo:
       for i in range (n):
           b+=((catalan_mem(i),memo)[0])*((catalan_mem(n-1-i),memo)[0])
    memo[n]=b
    return memo[n]    

谢谢!

解决方案

如果在memo中的n上调用catalan_mem,则将memo[n]替换为0.这可能不是您想要的. /p>

如果不进一步解析逻辑,这表明memo[n]=b应该在if块的内部.

I am tring to use memoization in order to calculate catalan numbers, but it just does not seem to work, what do I need to change?

def catalan_mem(n, memo = None):
    if n==0:
        return 1
    if memo == None:
        memo = {}
    b=0
    if n not in memo:
       for i in range (n):
           b+=((catalan_mem(i),memo)[0])*((catalan_mem(n-1-i),memo)[0])
    memo[n]=b
    return memo[n]    

thank you!

解决方案

If you call catalan_mem on an n in memo then you replace memo[n] with 0. This is probably not what you intend.

Without parsing the logic further, this suggests memo[n]=b should be inside of the if block.

这篇关于使用记忆来计算加泰罗尼亚语数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 05:16