题目: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