中级农民
- 积分
- 202
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-10-4
- 最后登录
- 1970-1-1
|
本帖最后由 wkh279 于 2015-7-17 20:13 编辑
最近才开始跟课程,贴一下代码哈
最后几问看了下答案,的确没有答案简
def square(x):
return x * x
def triple(x):
return 3 * x
def identity(x):
return x
def increment(x):
return x + 1
def piecewise(f, g, b):
"""Returns the piecewise function h where:
h(x) = f(x) if x < b,
g(x) otherwise
>>> def negate(x):
... return -x
>>> abs_value = piecewise(negate, identity, 0)
>>> abs_value(6)
6
>>> abs_value(-1)
1
"""
def h(x):
if x<b: return f(x)
else: return g(x)
return h
def repeated(f, n):
"""Return the function that computes the nth application of f.
>>> add_three = repeated(increment, 3)
>>> add_three(5)
8
>>> repeated(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1
243
>>> repeated(square, 2)(5) # square(square(5))
625
>>> repeated(square, 4)(5) # square(square(square(square(5))))
152587890625
"""
g=f
for i in range(n-1):
g=compose1(f,g)
return g
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
###################
# Church Numerals #
###################
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)"""
return f
def two(f):
"""Church numeral 2: same as successor(successor(zero))"""
return compose1(f,f)
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
"""
return n(increment)(0)
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
"""
x,y=church_to_int(m),church_to_int(n)
def g(f):
return repeated(f,x+y)
return g
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
"""
x,y=church_to_int(m),church_to_int(n)
def g(f):
return repeated(f,x*y)
return g
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
"""
x,y=church_to_int(m),church_to_int(n)
def g(f):
return repeated(f,x**y)
return g
|
|