12
返回列表 发新帖
楼主: goldpanda
跳转到指定楼层
上一主题 下一主题
收起左侧

[CS61A]Homework 3

🔗
reasonapp 2015-6-17 17:50:03 | 只看该作者
全局:
这次作业还是挺有难度的。pingpong那题想了我半天,hanoi写出来不难,把游戏规则想清楚也花了好久哈哈,看了群友写的代码之后发现确实还可以改进!上代码:
#hw03
#Q1
def g(n):
    """Return the value of G(n), computed recursively.

    >>> g(1)
    1
    >>> g(2)
    2
    >>> g(3)
    3
    >>> g(4)
    10
    >>> g(5)
    22
    """
    "*** YOUR CODE HERE ***"
    if n <= 3:
        return n
    if n >= 4:
        return g(n-1) + (2 * g(n-2)) + (3 * g(n-3))
        
def g_iter(n):
    """Return the value of G(n), computed iteratively.

    >>> g_iter(1)
    1
    >>> g_iter(2)
    2
    >>> g_iter(3)
    3
    >>> g_iter(4)
    10
    >>> g_iter(5)
    22
    """
    "*** YOUR CODE HERE ***"
    if n <= 3:
        return
    a , b, c = 1, 2, 3
    if n >= 4:
        while n > 3:
            a, b, c = b, c, c + 2*b + 3*a
            n = n - 1
        return c
        
#Q2
def has_seven(k):
    """Returns True if at least one of the digits of k is a 7, False otherwise.

    >>> has_seven(3)
    False
    >>> has_seven(7)
    True
    >>> has_seven(2734)
    True
    >>> has_seven(2634)
    False
    >>> has_seven(734)
    True
    >>> has_seven(7777)
    True
    """
    "*** YOUR CODE HERE ***"
    if k // 10 == 0:
        if k % 10 == 7:
            return True
        if k % 10 != 7:
            return False
    if k % 10 == 7:
        return True
    if k % 10 != 7:
        return has_seven(k//10)
        
#Q3
def pingpong(n):
    """Return the nth element of the ping-pong sequence.

    >>> pingpong(7)
    7
    >>> pingpong(8)
    6
    >>> pingpong(15)
    1
    >>> pingpong(21)
    -1
    >>> pingpong(22)
    0
    >>> pingpong(30)
    6
    >>> pingpong(68)
    2
    >>> pingpong(69)
    1
    >>> pingpong(70)
    0
    >>> pingpong(71)
    1
    >>> pingpong(72)
    0
    >>> pingpong(100)
    2
    """
    def pingpong_next(k, p, up):
        if k == n:
            return p
        if up:
            return pingpong_switch(k+1, p+1, up)
        else:
            return pingpong_switch(k+1, p-1, up)

    def pingpong_switch(k, p, up):
        if k % 7 == 0 or has_seven(k):
            return pingpong_next(k, p, not up)
        else:
            return pingpong_next(k, p, up)

    return pingpong_next(1, 1, True)
   
#Q4
def count_change(amount):
    """Return the number of ways to make change for amount.

    >>> count_change(7)
    6
    >>> count_change(10)
    14
    >>> count_change(20)
    60
    >>> count_change(100)
    9828
    """
    "*** YOUR CODE HERE ***"
    return count_min(1, amount)
   
def count_min(n,m):
    if n == m:
        return 1
    if n > m:
        return 0
    if m == 0:
        return 0
    else:
        with_min = count_min(n, m-n)
        without_min = count_min(2*n, m)
        return with_min + without_min   

#Q5
def towers_of_hanoi(n, start, end):
    """Print the moves required to solve the towers of hanoi game, starting
    with n disks on the start pole and finishing on the end pole.

    The game is to assumed to have 3 poles.

    >>> towers_of_hanoi(1, 1, 3)
    Move the top disk from rod 1 to rod 3
    >>> towers_of_hanoi(2, 1, 3)
    Move the top disk from rod 1 to rod 2
    Move the top disk from rod 1 to rod 3
    Move the top disk from rod 2 to rod 3
    >>> towers_of_hanoi(3, 1, 3)
    Move the top disk from rod 1 to rod 3
    Move the top disk from rod 1 to rod 2
    Move the top disk from rod 3 to rod 2
    Move the top disk from rod 1 to rod 3
    Move the top disk from rod 2 to rod 1
    Move the top disk from rod 2 to rod 3
    Move the top disk from rod 1 to rod 3
    """
    assert 0 < start <= 3 and 0 < end <= 3 and start != end, "Bad start/end"
    "*** YOUR CODE HERE ***"
    if n == 1:
        print "Move the top disk from rod " + str(start) + " to rod " + str(end)
    else:
        index =  start + end
        if index == 3:
            index = 3
        if index == 4:
            index = 2
        if index == 5:
            index = 1
        towers_of_hanoi(n-1, start, index)
        towers_of_hanoi(1, start, end)
        towers_of_hanoi(n-1, index, end)
回复

使用道具 举报

🔗
rockleecsu 2016-1-27 07:47:26 | 只看该作者
全局:
不愧是Berkeley,感觉一年级的第一门课难度就相当恐怖阿。。。。。我也学过好几门CS/CE课了,但是依然觉得作业有些难度,pingpong那题做了好久,count_change想不到好方法,就直接省事用DP做了,最后一个challenge是看了答案才理解的。。感觉lambda表达式确实学的一般。。。不过赶进度就不深究了,如果完全按照伯克利学生的标准,我的智商也不够。。
完成截图:


代码:
  1. def g(n):
  2.         """Return the value of G(n), computed recursively.

  3.         >>> g(1)
  4.         1
  5.         >>> g(2)
  6.         2
  7.         >>> g(3)
  8.         3
  9.         >>> g(4)
  10.         10
  11.         >>> g(5)
  12.         22
  13.         """
  14.         "*** YOUR CODE HERE ***"
  15.         if n <= 3:
  16.                 return n
  17.         return g(n-1) + 2 * g(n-2) + 3 * g(n-3)

  18. def g_iter(n):
  19.         """Return the value of G(n), computed iteratively.

  20.         >>> g_iter(1)
  21.         1
  22.         >>> g_iter(2)
  23.         2
  24.         >>> g_iter(3)
  25.         3
  26.         >>> g_iter(4)
  27.         10
  28.         >>> g_iter(5)
  29.         22
  30.         """
  31.         "*** YOUR CODE HERE ***"
  32.         g_list = (n + 1) * [0]
  33.         for i in range(n + 1):
  34.                 if i <= 3:
  35.                         g_list[i] = i
  36.                 else:
  37.                         g_list[i] = g_list[i-1] + 2 * g_list[i-2] + 3 * g_list[i-3]
  38.         return g_list[n]


  39. def has_seven(k):
  40.         """Returns True if at least one of the digits of k is a 7, False otherwise.

  41.         >>> has_seven(3)
  42.         False
  43.         >>> has_seven(7)
  44.         True
  45.         >>> has_seven(2734)
  46.         True
  47.         >>> has_seven(2634)
  48.         False
  49.         >>> has_seven(734)
  50.         True
  51.         >>> has_seven(7777)
  52.         True
  53.         """
  54.         "*** YOUR CODE HERE ***"
  55.         if k % 10 == 7:
  56.                 return True
  57.         if k < 10:
  58.                 return False
  59.         return has_seven(k // 10)


  60. def pingpong(n):
  61.         """Return the nth element of the ping-pong sequence.

  62.         >>> pingpong(7)
  63.         7
  64.         >>> pingpong(8)
  65.         6
  66.         >>> pingpong(15)
  67.         1
  68.         >>> pingpong(21)
  69.         -1
  70.         >>> pingpong(22)
  71.         0
  72.         >>> pingpong(30)
  73.         6
  74.         >>> pingpong(68)
  75.         2
  76.         >>> pingpong(69)
  77.         1
  78.         >>> pingpong(70)
  79.         0
  80.         >>> pingpong(71)
  81.         1
  82.         >>> pingpong(72)
  83.         0
  84.         >>> pingpong(100)
  85.         2
  86.         """
  87.         "*** YOUR CODE HERE ***"
  88.         def helper(k, increament, tmp):
  89.                 if k == n:
  90.                         return tmp
  91. #                print("test", n, increament)
  92.                 if k % 7 == 0 or has_seven(k):
  93.                         increament = -increament
  94.                 return helper(k+1, increament, tmp+increament)

  95.         return helper(1, 1, 1)


  96. def count_change(amount):
  97.         """Return the number of ways to make change for amount.

  98.         >>> count_change(7)
  99.         6
  100.         >>> count_change(10)
  101.         14
  102.         >>> count_change(20)
  103.         60
  104.         >>> count_change(100)
  105.         9828
  106.         """
  107.         "*** YOUR CODE HERE ***"
  108.         arr = []
  109.         i = 1
  110.         while i <= amount:
  111.                 arr.append(i)
  112.                 i *= 2

  113.         res = (amount + 1) * [0]
  114.         res[0] = 1

  115.         for i in range(len(arr)):
  116.                 for j in range(arr[i], amount + 1):
  117.                         res[j] = res[j] + res[j-arr[i]]                # sum arr[i] and including a[[i]]

  118.         return res[amount]
  119.        

  120. def towers_of_hanoi(n, start, end):
  121.         """Print the moves required to solve the towers of hanoi game, starting
  122.         with n disks on the start pole and finishing on the end pole.

  123.         The game is to assumed to have 3 poles.

  124.         >>> towers_of_hanoi(1, 1, 3)
  125.         Move the top disk from rod 1 to rod 3
  126.         >>> towers_of_hanoi(2, 1, 3)
  127.         Move the top disk from rod 1 to rod 2
  128.         Move the top disk from rod 1 to rod 3
  129.         Move the top disk from rod 2 to rod 3
  130.         >>> towers_of_hanoi(3, 1, 3)
  131.         Move the top disk from rod 1 to rod 3
  132.         Move the top disk from rod 1 to rod 2
  133.         Move the top disk from rod 3 to rod 2
  134.         Move the top disk from rod 1 to rod 3
  135.         Move the top disk from rod 2 to rod 1
  136.         Move the top disk from rod 2 to rod 3
  137.         Move the top disk from rod 1 to rod 3
  138.         """
  139.         assert 0 < start <= 3 and 0 < end <= 3 and start != end, "Bad start/end"
  140.         "*** YOUR CODE HERE ***"
  141.         def helper(n, start, end, empty):
  142.                 if n == 1:
  143.                         print("Move the top disk from rod %d to rod %d" % (start, end))
  144.                         return
  145.                 helper(n-1, start, empty, end)
  146.                 helper(1, start, end, empty)
  147.                 helper(n-1, empty, end, start)

  148.         return helper(n, start, end, 6 - start - end)


  149. from operator import sub, mul

  150. def make_anonymous_factorial():
  151.         """Return the value of an expression that computes factorial.

  152.         >>> make_anonymous_factorial()(5)
  153.         120
  154.         """
  155.         return lambda n: (lambda f, v: f(f, v))(lambda f, v: 1 if v == 1 else mul(v, f(f, sub(v, 1))), n)
复制代码
回复

使用道具 举报

🔗
Liaeve 2016-2-14 00:14:18 | 只看该作者
全局:
最后一道还是放弃了,不知道有没有人能推荐可以比较透彻学lambda用法的
def g(n):
    """Return the value of G(n), computed recursively.

    >>> g(1)
    1
    >>> g(2)
    2
    >>> g(3)
    3
    >>> g(4)
    10
    >>> g(5)
    22
    """
    "*** YOUR CODE HERE ***"
    if n == 1:
        return 1
    elif n == 2:
        return 2
    elif n == 3:
        return 3
    else:
        return g(n - 1) + 2 * g(n - 2) + 3 * g(n - 3)

def g_iter(n):
    """Return the value of G(n), computed iteratively.

    >>> g_iter(1)
    1
    >>> g_iter(2)
    2
    >>> g_iter(3)
    3
    >>> g_iter(4)
    10
    >>> g_iter(5)
    22
    """
    "*** YOUR CODE HERE ***"
    a = 1
    b = 2
    c = 3
    if n < 4:
        gn = n
    for i in range(4, n+1):
        gn = c + 2 * b + 3 * a
        a = b
        b = c
        c = gn
    return gn

def has_seven(k):
    """Returns True if at least one of the digits of k is a 7, False otherwise.

    >>> has_seven(3)
    False
    >>> has_seven(7)
    True
    >>> has_seven(2734)
    True
    >>> has_seven(2634)
    False
    >>> has_seven(734)
    True
    >>> has_seven(7777)
    True
    """
    "*** YOUR CODE HERE ***"
    if (k % 10) % 7 == 0:
        return True
    elif k // 10 == 0:
        return False
    else:
        return has_seven(k // 10)


def pingpong(n):
    """Return the nth element of the ping-pong sequence.

    >>> pingpong(7)
    7
    >>> pingpong(8)
    6
    >>> pingpong(15)
    1
    >>> pingpong(21)
    -1
    >>> pingpong(22)
    0
    >>> pingpong(30)
    6
    >>> pingpong(68)
    2
    >>> pingpong(69)
    1
    >>> pingpong(70)
    0
    >>> pingpong(71)
    1
    >>> pingpong(72)
    0
    >>> pingpong(100)
    2
    """
    "*** YOUR CODE HERE ***"
    def count(n):
        if n == 1:
            return 0
        elif (n-1) % 7 == 0 or (n-1) % 10 == 7 or (n-1) // 10 == 7:
            return count(n-1) + 1
        else:
            return count(n-1)
    if n == 1:
        return 1
    else:
        return pingpong(n-1) + pow(-1, count(n))


def count_change(amount):
    """Return the number of ways to make change for amount.

    >>> count_change(7)
    6
    >>> count_change(10)
    14
    >>> count_change(20)
    60
    >>> count_change(100)
    9828
    """
    "*** YOUR CODE HERE ***"
    def count(amount , parts):
        if amount == 0:
            return 1
        elif amount < 0:
            return 0
        elif parts > amount:
            return 0
        else:
            with_parts = count(amount - parts, parts)
            without_parts = count(amount, parts * 2)
            return with_parts + without_parts
    return count(amount, 1)


def towers_of_hanoi(n, start, end):
    """Print the moves required to solve the towers of hanoi game, starting
    with n disks on the start pole and finishing on the end pole.

    The game is to assumed to have 3 poles.

    >>> towers_of_hanoi(1, 1, 3)
    Move the top disk from rod 1 to rod 3
    >>> towers_of_hanoi(2, 1, 3)
    Move the top disk from rod 1 to rod 2
    Move the top disk from rod 1 to rod 3
    Move the top disk from rod 2 to rod 3
    >>> towers_of_hanoi(3, 1, 3)
    Move the top disk from rod 1 to rod 3
    Move the top disk from rod 1 to rod 2
    Move the top disk from rod 3 to rod 2
    Move the top disk from rod 1 to rod 3
    Move the top disk from rod 2 to rod 1
    Move the top disk from rod 2 to rod 3
    Move the top disk from rod 1 to rod 3
    """
    assert 0 < start <= 3 and 0 < end <= 3 and start != end, "Bad start/end"
    "*** YOUR CODE HERE ***"
    if n == 1:
        print ('Move the top disk from rod', start, 'to rod', end)
    else:
        other = 6 - start - end
        towers_of_hanoi(n-1, start, other)
        towers_of_hanoi(1, start, end)
        towers_of_hanoi(n-1, other, end)


from operator import sub, mul

def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    """
    return 'YOUR_EXPRESSION_HERE'
回复

使用道具 举报

🔗
wkh279 2016-11-20 21:33:49 | 只看该作者
全局:
Question 6: Challenge Problem想了好久没想出来,看了答案才明白
这次作业难度有点呀
  1. def g(n):
  2.     """Return the value of G(n), computed recursively.

  3.     >>> g(1)
  4.     1
  5.     >>> g(2)
  6.     2
  7.     >>> g(3)
  8.     3
  9.     >>> g(4)
  10.     10
  11.     >>> g(5)
  12.     22
  13.     """
  14.     if n<=3:
  15.         return n
  16.     else:
  17.         return g(n-1)+g(n-2)*2+g(n-3)*3

  18. def g_iter(n):
  19.     """Return the value of G(n), computed iteratively.

  20.     >>> g_iter(1)
  21.     1
  22.     >>> g_iter(2)
  23.     2
  24.     >>> g_iter(3)
  25.     3
  26.     >>> g_iter(4)
  27.     10
  28.     >>> g_iter(5)
  29.     22
  30.     """
  31.     a,b,c,d=1,2,3,10
  32.     for _ in range(1,n):
  33.         a,b,c,d=b,c,d,3*b+2*c+d
  34.     return a

  35. def has_seven(k):
  36.     """Returns True if at least one of the digits of k is a 7, False otherwise.

  37.     >>> has_seven(3)
  38.     False
  39.     >>> has_seven(7)
  40.     True
  41.     >>> has_seven(2734)
  42.     True
  43.     >>> has_seven(2634)
  44.     False
  45.     >>> has_seven(734)
  46.     True
  47.     >>> has_seven(7777)
  48.     True
  49.     """
  50.     if k<10:
  51.         if k==7:
  52.             return True
  53.         return False
  54.     else:
  55.         return has_seven(k//10) or has_seven(k%10)

  56. def pingpong(n):
  57.     """Return the nth element of the ping-pong sequence.

  58.     >>> pingpong(7)
  59.     7
  60.     >>> pingpong(8)
  61.     6
  62.     >>> pingpong(15)
  63.     1
  64.     >>> pingpong(21)
  65.     -1
  66.     >>> pingpong(22)
  67.     0
  68.     >>> pingpong(30)
  69.     6
  70.     >>> pingpong(68)
  71.     2
  72.     >>> pingpong(69)
  73.     1
  74.     >>> pingpong(70)
  75.     0
  76.     >>> pingpong(71)
  77.     1
  78.     >>> pingpong(72)
  79.     0
  80.     >>> pingpong(100)
  81.     2
  82.     """
  83.     if n<8:
  84.         return n
  85.     # function up_down returns a value, which equals to pingpong(m+1)-pingpong(m)
  86.     def up_down(m):
  87.         if m<7:
  88.             return 1
  89.         if m%7==0 or has_seven(m):
  90.             return -1*up_down(m-1)
  91.         else:
  92.             return up_down(m-1)
  93.     return pingpong(n-1)+up_down(n-1)


  94.    
  95. def count_change(amount):
  96.     """Return the number of ways to make change for amount.

  97.     >>> count_change(7)
  98.     6
  99.     >>> count_change(10)
  100.     14
  101.     >>> count_change(20)
  102.     60
  103.     >>> count_change(100)
  104.     9828
  105.     """
  106.     def count(min_change,amount):
  107.         if amount<0:
  108.             return 0
  109.         elif amount==0:
  110.             return 1
  111.         elif amount<min_change:
  112.             return 0
  113.         else:
  114.             return count(min_change,amount-min_change)+count(min_change*2,amount)
  115.     return count(1,amount)
  116.    

  117. def towers_of_hanoi(n, start, end):
  118.     """Print the moves required to solve the towers of hanoi game, starting
  119.     with n disks on the start pole and finishing on the end pole.

  120.     The game is to assumed to have 3 poles.

  121.     >>> towers_of_hanoi(1, 1, 3)
  122.     Move the top disk from rod 1 to rod 3
  123.     >>> towers_of_hanoi(2, 1, 3)
  124.     Move the top disk from rod 1 to rod 2
  125.     Move the top disk from rod 1 to rod 3
  126.     Move the top disk from rod 2 to rod 3
  127.     >>> towers_of_hanoi(3, 1, 3)
  128.     Move the top disk from rod 1 to rod 3
  129.     Move the top disk from rod 1 to rod 2
  130.     Move the top disk from rod 3 to rod 2
  131.     Move the top disk from rod 1 to rod 3
  132.     Move the top disk from rod 2 to rod 1
  133.     Move the top disk from rod 2 to rod 3
  134.     Move the top disk from rod 1 to rod 3
  135.     """
  136.     assert 0 < start <= 3 and 0 < end <= 3 and start != end, "Bad start/end"
  137.     if n==1:
  138.             print("Move the top disk from rod "+str(start)+" to rod "+str(end))
  139.     else:
  140.             _= towers_of_hanoi(n-1,start,6-start-end)
  141.             _= towers_of_hanoi(1,start,end)
  142.             _= towers_of_hanoi(n-1,6-start-end,end)

  143. from operator import sub, mul

  144. def make_anonymous_factorial():
  145.     """Return the value of an expression that computes factorial.

  146.     >>> make_anonymous_factorial()(5)
  147.     120
  148.     """
复制代码
回复

使用道具 举报

🔗
续命神哈 2016-12-15 19:56:05 | 只看该作者
全局:
wkh279 发表于 2016-11-20 21:33
Question 6: Challenge Problem想了好久没想出来,看了答案才明白
这次作业难度有点呀

同学, 请问你是在哪看的视频?有字幕吗
我的视频没字幕好蛋疼。。。
回复

使用道具 举报

🔗
davewww 2018-7-17 08:51:16 | 只看该作者
全局:
交作业了,代码在此:

HW_SOURCE_FILE = 'hw03.py'

#############
# Questions #
#############

def has_seven(k):
    """Returns True if at least one of the digits of k is a 7, False otherwise.

    >>> has_seven(3)
    False
    >>> has_seven(7)
    True
    >>> has_seven(2734)
    True
    >>> has_seven(2634)
    False
    >>> has_seven(734)
    True
    >>> has_seven(7777)
    True
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'has_seven',
    ...       ['Assign', 'AugAssign'])
    True
    """
    if k%10 == 7:
        return True
    elif k<10:
        return False
    else:
        return has_seven(k//10)

def summation(n, term):

    """Return the sum of the first n terms in the sequence defined by term.
    Implement using recursion!

    >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
    225
    >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
    54
    >>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5
    62
    >>> # Do not use while/for loops!
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'summation',
    ...       ['While', 'For'])
    True
    """
    assert n >= 1
    "*** YOUR CODE HERE ***"
    if n == 1:
        return term(n)
    else:
        return summation(n-1, term) + term(n)

def square(x):
    return x * x

def identity(x):
    return x

triple = lambda x: 3 * x

increment = lambda x: x + 1

add = lambda x, y: x + y

mul = lambda x, y: x * y

def accumulate(combiner, base, n, term):
    """Return the result of combining the first n terms in a sequence and base.
    The terms to be combined are term(1), term(2), ..., term(n).  combiner is a
    two-argument commutative function.

    >>> accumulate(add, 0, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
    15
    >>> accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5
    26
    >>> accumulate(add, 11, 0, identity) # 11
    11
    >>> accumulate(add, 11, 3, square)   # 11 + 1^2 + 2^2 + 3^2
    25
    >>> accumulate(mul, 2, 3, square)   # 2 * 1^2 * 2^2 * 3^2
    72
    """
    "*** YOUR CODE HERE ***"

    if n == 0:
        return combiner(base, 0)

    elif n == 1:
        return combiner(base, term(1))

    else:
        return combiner(accumulate(combiner, base, n-1, term), term(n))



def summation_using_accumulate(n, term):
    """Returns the sum of term(1) + ... + term(n). The implementation
    uses accumulate.

    >>> summation_using_accumulate(5, square)
    55
    >>> summation_using_accumulate(5, triple)
    45
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'summation_using_accumulate',
    ...       ['Recursion', 'For', 'While'])
    True
    """
    "*** YOUR CODE HERE ***"
    return accumulate(add, 0, n, term)

def product_using_accumulate(n, term):
    """An implementation of product using accumulate.

    >>> product_using_accumulate(4, square)
    576
    >>> product_using_accumulate(6, triple)
    524880
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'product_using_accumulate',
    ...       ['Recursion', 'For', 'While'])
    True
    """
    "*** YOUR CODE HERE ***"
    return accumulate(mul,1, n, term)

def filtered_accumulate(combiner, base, pred, n, term):
    """Return the result of combining the terms in a sequence of N terms
    that satisfy the predicate pred. combiner is a two-argument function.
    If v1, v2, ..., vk are the values in term(1), term(2), ..., term(N)
    that satisfy pred, then the result is
         base combiner v1 combiner v2 ... combiner vk
    (treating combiner as if it were a binary operator, like +). The
    implementation uses accumulate.

    >>> filtered_accumulate(add, 0, lambda x: True, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
    15
    >>> filtered_accumulate(add, 11, lambda x: False, 5, identity) # 11
    11
    >>> filtered_accumulate(add, 0, odd, 5, identity)   # 0 + 1 + 3 + 5
    9
    >>> filtered_accumulate(mul, 1, greater_than_5, 5, square)  # 1 * 9 * 16 * 25
    3600
    >>> # Do not use while/for loops or recursion
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'filtered_accumulate',
    ...       ['While', 'For', 'Recursion'])
    True
    """
    def combine_if(x, y):

        "*** YOUR CODE HERE ***"
        if pred(y) == True:
            return combiner(x, y)
        else:
            return x

    return accumulate(combine_if, base, n, term)

def odd(x):
    return x % 2 == 1

def greater_than_5(x):
    return x > 5

def make_repeater(f, n):
    """Return the function that computes the nth application of f.

    >>> add_three = make_repeater(increment, 3)
    >>> add_three(5)
    8
    >>> make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1
    243
    >>> make_repeater(square, 2)(5) # square(square(5))
    625
    >>> make_repeater(square, 4)(5) # square(square(square(square(5))))
    152587890625
    >>> make_repeater(square, 0)(5)
    5
    """
    "*** YOUR CODE HERE ***"
    def h(x):
        k = 0
        while k < n:
            x, k = f(x), k + 1
        return x
    return h     

def compose1(f, g):
    """Return a function h, such that h(x) = f(g(x))."""
    def h(x):
        return f(g(x))
    return h

###################
# Extra Questions #
###################

quine = """
"*** YOUR CODE HERE ***"
"""

def zero(f):
    return lambda x: x

def successor(n):
    return lambda f: lambda x: f(n(f)(x))

def one(f):
    """Church numeral 1: same as successor(zero)"""
    "*** YOUR CODE HERE ***"

def two(f):
    """Church numeral 2: same as successor(successor(zero))"""
    "*** YOUR CODE HERE ***"

three = successor(two)

def church_to_int(n):
    """Convert the Church numeral n to a Python integer.

    >>> church_to_int(zero)
    0
    >>> church_to_int(one)
    1
    >>> church_to_int(two)
    2
    >>> church_to_int(three)
    3
    """
    "*** YOUR CODE HERE ***"

def add_church(m, n):
    """Return the Church numeral for m + n, for Church numerals m and n.

    >>> church_to_int(add_church(two, three))
    5
    """
    "*** YOUR CODE HERE ***"

def mul_church(m, n):
    """Return the Church numeral for m * n, for Church numerals m and n.

    >>> four = successor(three)
    >>> church_to_int(mul_church(two, three))
    6
    >>> church_to_int(mul_church(three, four))
    12
    """
    "*** YOUR CODE HERE ***"

def pow_church(m, n):
    """Return the Church numeral m ** n, for Church numerals m and n.

    >>> church_to_int(pow_church(two, three))
    8
    >>> church_to_int(pow_church(three, two))
    9
    """
    "*** YOUR CODE HERE ***"
回复

使用道具 举报

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

本版积分规则

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