Problem 8: All-Ys Has Been (2pts)
Problem
Given mystery function
Y, completefib_makerandnumber_of_six_makerso that the given doctests work correctly.When
Yis called onfib_maker, it should return a function which takes a positive integernand returns thenth Fibonacci number.Similarly, when
Yis called onnumber_of_six_makerit should return a function that takes a positive integerxand returns the number of times the digit 6 appears inx.
给定神秘函数 Y,完成 fib_maker 和 number_of_six_maker,使给定的 doctest 能够正常工作。
当 Y 在 fib_maker 上被调用时,它应该返回一个函数,该函数接受一个正整数 n 并返回第 n 个斐波那契数。
类似地,当 Y 在 number_of_six_maker 上被调用时,它应该返回一个函数,该函数接受一个正整数 x 并返回数字 6 在 x 中出现的次数。
def Y(f): return (lambda x: x(x))(lambda x: f(lambda z: x(x)(z)))
def fib_maker(f): return lambda r: 'YOUR_EXPRESSION_HERE'
def number_of_six_maker(f): return lambda r: 'YOUR_EXPRESSION_HERE'
my_fib = Y(fib_maker)
my_number_of_six = Y(number_of_six_maker)
# This code sets up doctests for my_fib and my_number_of_six.
my_fib.__name__ = 'my_fib'
my_fib.__doc__ = """Given n, returns the nth Fibonacci nuimber.
>>> my_fib(0)
0
>>> my_fib(1)
1
>>> my_fib(2)
1
>>> my_fib(3)
2
>>> my_fib(4)
3
>>> my_fib(5)
5
"""
my_number_of_six.__name__ = 'my_number_of_six'
my_number_of_six.__doc__ = """Return the number of 6 in each digit of a positive integer n.
>>> my_number_of_six(666)
3
>>> my_number_of_six(123456)
1
"""
Hints
Hint: You may use the ternary operator
<a> if <bool-exp> else <b>, which evaluates to<a>if<bool-exp>is truthy and evaluates to<b>if<bool-exp>is false-y.
-
你可以使用三元运算符
<a> if <bool-exp> else <b>,它在<bool-exp>为真值时求值为<a>,在<bool-exp>为假值时求值为<b>。 -
不要把题目想的太复杂。
-
这个“神秘函数”叫“Y 组合子”。有兴趣可以查查资料。