编写异常函数
Writing an exception function
我目前正在在线学习平台上学习,我的代码必须通过测试用例(包括在下面)
问题如下:
写一个高阶函数 exception_function 它将 return 一个有异常的函数。 exception_function 应该接受一个函数 f(x)、一个整数输入和一个整数输出,return 另一个函数 g(x)。 g(x) 的输出应该与 f(x) 相同,只是当 x 与整数输入相同时,输出将是 returned.
例如,假设我们有一个函数 sqrt,它 return 是参数的平方根。使用 new_sqrt = exception_function(sqrt, 7, 2) 我们得到 new_sqrt,除了 new_sqrt(7) 之外,它的行为类似于 sqrt,其中 2 的值将是return编辑。
下面是答案模板
from math import *
def exception_function(f, rejected_input, new_output):
"""Your code here"""
pass
#################
#DO NOT REMOVE#
#################
new_sqrt = exception_function(sqrt, 7, 2)
测试用例:
new_sqrt(9) - 预期答案 3
new_sqrt(7) - 预期答案 2
这是我不确定的地方。
- 如何在不改变 f 本身的情况下控制 f return 的内容?
非常感谢您的宝贵时间。
成功解决!
def exception_function(f, rejected_input, new_output):
def inner_function(x):
if x==rejected_input:
return new_output
else:
return f(x)
return inner_function
new_sqrt = exception_function(sqrt, 7, 2)
我目前正在在线学习平台上学习,我的代码必须通过测试用例(包括在下面) 问题如下:
写一个高阶函数 exception_function 它将 return 一个有异常的函数。 exception_function 应该接受一个函数 f(x)、一个整数输入和一个整数输出,return 另一个函数 g(x)。 g(x) 的输出应该与 f(x) 相同,只是当 x 与整数输入相同时,输出将是 returned.
例如,假设我们有一个函数 sqrt,它 return 是参数的平方根。使用 new_sqrt = exception_function(sqrt, 7, 2) 我们得到 new_sqrt,除了 new_sqrt(7) 之外,它的行为类似于 sqrt,其中 2 的值将是return编辑。
下面是答案模板
from math import *
def exception_function(f, rejected_input, new_output):
"""Your code here"""
pass
#################
#DO NOT REMOVE#
#################
new_sqrt = exception_function(sqrt, 7, 2)
测试用例:
new_sqrt(9) - 预期答案 3
new_sqrt(7) - 预期答案 2
这是我不确定的地方。
- 如何在不改变 f 本身的情况下控制 f return 的内容?
非常感谢您的宝贵时间。
成功解决!
def exception_function(f, rejected_input, new_output):
def inner_function(x):
if x==rejected_input:
return new_output
else:
return f(x)
return inner_function
new_sqrt = exception_function(sqrt, 7, 2)