关于CS61A的Lab3中Interleaved Sum的答案

题目:Write a function interleaved_sum that similarly computes the sum of a sequence of terms from 1 to n, but uses different functions to compute the terms for odd and even numbers. Do so without using any loops or testing in any way if a number is odd or even. (You may test if a number is equal to 0, 1, or n.)

Hint: Use recursion and a helper function!

分析:这道题非常有意思。题中限制了我们不能使用循环,也不能以任何一种方式去判断n是偶数还是奇数,于是我们得想一个递归的方法,让函数从0计算到n,而不是从n计算到0,这就是自定义函数sum_from_i_to_n要做的事情。本题我的代码如下,如有错误或者有更好的思路,敬请大家批评指正:

def interleaved_sum(n, odd_term, even_term):
    """Compute the sum odd_term(1) + even_term(2) + odd_term(3) + ..., up
    to n.

    >>> # 1 + 2^2 + 3 + 4^2 + 5
    ... interleaved_sum(5, lambda x: x, lambda x: x*x)
    29
    """
    "*** YOUR CODE HERE ***"
    def sum_from_i_t
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值