CS61Asp24_HW03_Interleaved Sum

问题描述

Write a function interleaved_sum, which takes in a number n and two one-argument functions: odd_func and even_func. It applies odd_func to every odd number and even_func to every even number from 1 to n including n and returns the sum.

For example, executing interleaved_sum(5, lambda x: x, lambda x: x * x) returns 1 + 2*2 + 3 + 4*4 + 5 = 29.

Implement this function without using any loops or directly testing if a number is odd or even -- no modulos (%) allowed! Instead of checking whether a number is even or odd, start with 1, which you know is an odd number.

Hint: Introduce an inner helper function that takes an odd number k and computes an interleaved sum from k to n (including n).

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

    >>> identity = lambda x: x
    >>> square = lambda x: x * x
    >>> triple = lambda x: x * 3
    >>> interleaved_sum(5, identity, square) # 1   + 2*2 + 3   + 4*4 + 5
    29
    >>> interleaved_sum(5, square, identity) # 1*1 + 2   + 3*3 + 4   + 5*5
    41
    >>> interleaved_sum(4, triple, square)   # 1*3 + 2*2 + 3*3 + 4*4
    32
    >>> interleaved_sum(4, square, triple)   # 1*1 + 2*3 + 3*3 + 4*3
    28
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'interleaved_sum', ['While', 'For', 'Mod']) # ban loops and %
    True
    """
    "*** YOUR CODE HERE ***"

题目分析

题目要求实现一个interleaved_sum函数,有三个参数:整数n,有一个参数的函数odd_func和even_func,对从1到n的偶数使用even_func函数,对奇数使用odd_func函数,最终返回各个函数的返回值之和。

要求不对数字的奇偶性进行判断(即不能用%运算符),并要求使用递归来实现(不能使用循环语句)。

解决这个问题可以使用一个内部函数helper,从1开始到n进行递归处理并求和。由于不能对特定数字进行奇偶性的判断,但已知1是奇数,因此让helper函数接受两个参数:当前处理的数字k和布尔值is_odd来表示是否是奇数。

由于不知道n的奇偶性,递归从1开始(k = 1, is_odd = True),base case是k > n的情况。递归过程中如果k是奇数,那么return odd_func(k) + helper(k + 1, False),如果k是偶数,return even_func(k) + helper(k + 1, True),如果k > n, 返回0。从而实现从1开始到n的各个整数对应的奇偶函数之和。

代码实现

def interleaved_sum(n, odd_func, even_func):
    def helper(k, is_odd):
        if k > n:
            return 0
        elif is_odd:
            return odd_func(k) + helper(k + 1, False)
        else:
            return even_func(k) + helper(k + 1, True)
    return helper(1, True)

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值