<
查看: 1252| 回复: 3
收起左侧

Berkeley CS61a 20fall lab02 问题请教

saintphoenix | 显示全部楼层
本楼:   👍  0
0%
0%
0   👎
全局:   0
0%
0%
0
公开课

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
小白不知道请教问题是不是在这里发帖
先把问题和答案发一下
def count_cond(condition):
    """Returns a function with one parameter N that counts all the numbers from
    1 to N that satisfy the two-argument predicate function Condition, where
    the first argument for Condition is N and the second argument is the
    number from 1 to N.
    >>> count_factors = count_cond(lambda n, i: n % i == 0)
    >>> count_factors(2)   # 1, 2
    2
    >>> count_factors(4)   # 1, 2, 4
    3
    >>> count_factors(12)  # 1, 2, 3, 4, 6, 12
    6
    >>> is_prime = lambda n, i: count_factors(i) == 2
    >>> count_primes = count_cond(is_prime)
    >>> count_primes(2)    # 2
    1
    >>> count_primes(3)    # 2, 3
    2
    >>> count_primes(4)    # 2, 3
    2
    >>> count_primes(5)    # 2, 3, 5
    3
    >>> count_primes(20)   # 2, 3, 5, 7, 11, 13, 17, 19
    8
    """
        def counter(n):
        i = 1
        count = 0
        while i <= n:
            if condition(n, i):
                count += 1
            i += 1
        return count
    return counter

小白一开始写成如下,就是答案没有套用一个def,结果报错。
        i = 1
        count = 0
        while i <= n:
            if condition(n, i):
                count += 1
            i += 1
        return count

但是小白没想明白为什么一定需要函数套函数?请大神们指点迷津。



上一篇:剑桥大学教授亲授《深度神经网络》Deep Neural Networks Course Taught by
下一篇:CS61B fall 2021 有小伙伴分享hw 和lab资料吗
regex 2021-10-10 08:49:40 来自APP | 显示全部楼层
本楼:   👍  0
0%
0%
0   👎
全局:   335
92%
8%
30
因为人家题目里说了让你接受一个函数作为参数,然后返回一个函数,这个函数再接受一个数n判断从1到n,有多少满足接受的函数条件的。你只有一个函数,n从哪接收?
回复

使用道具 举报

 楼主| saintphoenix 2021-10-10 09:50:29 | 显示全部楼层
本楼:   👍  0
0%
0%
0   👎
全局:   0
0%
0%
0
谢谢解答
回复

使用道具 举报

exexeiei 2021-10-11 05:59:39 | 显示全部楼层
本楼:   👍  0
0%
0%
0   👎
全局:   0
0%
0%
0
我也在学20fall这个版本,想一起学习可加微信:hanniballei
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

Advertisement
>
快速回复 返回顶部 返回列表