ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

UCB CS 61A - I Heard You Liked Functions...

2021-09-03 16:00:45  阅读:331  来源: 互联网

标签:... Liked f3 return f1 Functions f2 def cycle


Problem

Define a function cycle that takes in three functions f1, f2, f3, as arguments. cycle will return another function that should take in an integer argument n and return another function. That final function should take in an argument x and cycle through applying f1, f2, and f3 to x, depending on what n was. Here's what the final function should do to x for a few values of n:

  • n = 0, return x
  • n = 1, apply f1 to x, or return f1(x)
  • n = 2, apply f1 to x and then f2 to the result of that, or return f2(f1(x))
  • n = 3, apply f1 to x, f2 to the result of applying f1, and then f3 to the result of applying f2, or f3(f2(f1(x)))
  • n = 4, start the cycle again applying f1, then f2, then f3, then f1 again, or f1(f3(f2(f1(x))))
  • And so forth.

Solution

"""
Returns a function that is itself a higher-order function.    

>>> def add1(x):
...     return x + 1
>>> def times2(x):
...     return x * 2
>>> def add3(x):
...     return x + 3
>>> my_cycle = cycle(add1, times2, add3)
>>> identity = my_cycle(0)
>>> identity(5)
5
>>> add_one_then_double = my_cycle(2)
>>> add_one_then_double(1)
4
>>> do_all_functions = my_cycle(3)
>>> do_all_functions(2)
9
>>> do_more_than_a_cycle = my_cycle(4)
>>> do_more_than_a_cycle(2)
10
>>> do_two_cycles = my_cycle(6)
>>> do_two_cycles(1)
19
"""

Iterative

def cycle(f1, f2, f3):
    def set_iteration(n):
        def set_initial(x):
            for i in range(1, n + 1):
                if i % 3 == 1:
                    x = f1(x)
                elif i % 3 == 2:
                    x = f2(x)
                else:
                    x = f3(x)
            return x
        return set_initial
    return set_iteration

Recursive

def cycle(f1, f2, f3):
    def wrapped(n):
        def set_initial(x):
            if n == 0:
                return x
            else:
                if n % 3 == 1:
                    return f1(wrapped(n - 1)(x))
                elif n % 3 == 2:
                    return f2(wrapped(n - 1)(x))
                else:
                    return f3(wrapped(n - 1)(x))
        return set_initial
    return wrapped

标签:...,Liked,f3,return,f1,Functions,f2,def,cycle
来源: https://www.cnblogs.com/stO-Orz/p/15223466.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有