总结一个递归函数的结果

诺姆

我正在尝试的问题是关于代码战的 XY140Z-n 星球上的融资计划。在此处输入链接描述内容为:我需要省钱买礼物。我想我可以做这样的事情:

第一周 (W0) 我周日不存任何东西,周一 1 点,周二 2 点...周六 6 点,第二周 (W1) 周一 2 点...周六 7 点等等,根据下表编号从 0 到 6。

你能告诉我,在我存了 12 个之后,周六晚上我的礼物要多少钱吗?(您的函数 finance(6) 应返回 168,这是表中节省的总和)。

想象一下,现在我们生活在 XY140Z-n 星球上,其中一周中的天数从 0 到 n(整数 n > 0),并且我从第 0 周保存到第 n 周(在下表中 n = 6) .

我在 XY140Z-n 星球上的融资计划结束时会有多少钱?

这个问题不需要递归,但我想练习它,这似乎是一个完美的问题。

到目前为止我创建的代码

def finance(n):
    if n <= 1:
        return 3
    else:
        total = (finance(n-1) + n*3)
        print(total)
    return total 

print(finance(6))

它部分对我有用,它确实给了我我每天可以节省的钱,我需要的是所有节省的钱的总和,我不知道该怎么做。我尝试了全局变量,尝试了其他一些方法,但每次都失败。

另外,如果有人可以解释不同的数学方法来计算这个,我会很感激。老实说,数学思维对我来说是问题中最难的部分,我发现的唯一模式是,与前一天相比,每天的储蓄增加了 +3。

特洛伊船长

如果您有兴趣,这是我的递归解决方案:

def finance(n):
    # when n = 6 for example, it means that the week has 7 days
    # idk why, kinda weird, but the problem definition is like this
    
    # recursive solution(n, n+1) yields the sum of savings 
    # for weeks `0` to `n` (first argument) 
    # for weeks of size `n+1` (second argument)
    return recursive_solution(n, n + 1)

def recursive_solution(week, size):
    if week == 0:
        # if the week in question is the first week
        # return the sum of arithmetic series `0, 1, ..., n`        

        return ((size - 1) * size) // 2  
    else:
        # for any other week
        # remember, calculating the sum of weeks from `0` to `week`
 
        # if this is any of the middle weeks, the arithmetic 
        # series is actually from `2*week` to `size+week`
        # which is equal to this, after reduction 
 
        current_week_value = ((size - 1 + 3 * week) * (size - week)) // 2
        
        # for the return value, take the savings computed for current 
        # week and add all the previous weeks (recursively)
        return current_day_value + recursive_solution(week - 1, size)

这里,recursive_solution(n, n+1)是从周到0n定周大小的全天节省的总和n+1我使用递归将结果相加,单个周的节省是算术系列的总和。上周计算的储蓄n从储蓄从几周0n-1是不是足够简单打扰一下它。然而,您可以n一周的储蓄中计算出一周的储蓄n-1——答案是

savings(n) = savings(n-1) - n*3 + week_size

- n*3来自删除n-1一周中一天的储蓄n-1,这正是n*2,另一个n来自现在您必须添加的事实week_size - n,因为每个剩余天(nweek_size-1的储蓄增加了1

更好地理解递归求和

看看这个计算数字总和的简单函数0 + 1 + ... + n

def summation(n):
    if n == 0:
        return 0
    else:
        return n + summation(n - 1)

这些陈述是正确的:

  1. 如果summation(n - 1)返回为总和0最多n-1,然后summation(n)返回n+为总和0达到n-1,这对于总和0最多n
  2. summation(0)is 0,这是原始和的正确结果0 + 1 + ... + n,因为整个序列只是初始0

现在替换第一个语句中的第二个语句。你知道这summation(0)是正确的,因此summation(1 - 1)是正确的,因此summation(1),因此summation(2),等等。它被称为归纳证明,尽管非常简单。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章