关于实现与if语句相同功能的Python函数的查询
我写了一个解决方案来回答下面的问题。
问题:我们来试着写一个函数,它的功能和 if 语句一样:
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and false_result otherwise."""
if condition:
return true_result
else:
return false_result
这个函数其实在所有情况下并不完全和 if 语句一样。为了证明这一点,请写出函数 c、t 和 f,使得其中一个函数返回数字 1,但其他的函数不返回:
def with_if_statement():
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
def c():
"*** YOUR CODE HERE ***"
def t():
"*** YOUR CODE HERE ***"
def f():
"*** YOUR CODE HERE ***"
解决方案:
>>> def c():
return 2 < 3
>>> def t():
return 2 < 3
>>> def f():
return not 2 < 3
>>> print(with_if_function())
True
>>>
我的问题是:
你能确认一下我的解决方案是否正确吗?
或者
你觉得我还没有完全理解这个问题吗?
3 个回答
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and
false_result otherwise.
>>> if_function(True, 2, 3)
2
>>> if_function(False, 2, 3)
3
>>> if_function(3==2, 3+2, 3-2)
1
>>> if_function(3>2, 3+2, 3-2)
5
"""
if condition:
return true_result
else:
return false_result
def with_if_statement():
"""
>>> with_if_statement()
1
"""
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
def c():
return True
def t():
return 1
def f():
'1'.sort()
这个问题要求我们写三个函数:c
、t
和 f
,使得 with_if_statement
返回 1
,而 with_if_function
不返回 1
(但可以做其他任何事情)。
一开始,这个问题看起来有点荒谬,因为从逻辑上讲,with_if_statement
和 with_if_function
的返回结果应该是一样的。然而,如果我们从解释器的角度来看这两个函数,它们其实是不同的。
函数 with_if_function
使用了一种调用表达式,这保证了它所有的操作数子表达式会在 if_function
应用到结果参数之前被计算。因此,即使 c
返回 False
,函数 t
仍然会被调用。相反,如果 with_if_statement
中的 c
返回 False
,那么 t
就不会被调用。(来自UCB网站)
你可能没有注意到,你传递给 if_function
的是你函数的 结果,而不是函数本身。所以这段代码:
if_function(c(), t(), f())
...其实是等同于:
_c = c()
_t = t()
_f = f()
if_function(_c, _t, _f)
也就是说,你的 condition
函数、true_result
函数和 false_result
函数都是在调用 if_function
之前就被执行了。
不过,只要稍微多花点心思,就能让它们看起来更相似:
def delayed_call(x):
# if x is a function, call it and return the result, otherwise return x
return x() if hasattr(x, '__call__') else x
def if_function(condition, true_result, false_result):
if delayed_call(condition):
return delayed_call(true_result)
else:
return delayed_call(false_result)
这样一来,if_function(c(), t(), f())
就变成了 if_function(c, t, f)
我理解这个问题是,你需要写出 c()
、f()
和 t()
这三个函数,使得 with_if_statement()
和 with_if_function()
返回的结果不一样。
根据你给出的定义,这两个函数现在都返回 True
,这说明你的解决方案是不正确的。
我相信几乎肯定有多种解决方案,但这里有一个可能的解决方案:
def c():
"*** YOUR CODE HERE ***"
return True
def t():
"*** YOUR CODE HERE ***"
if not hasattr(f, "beencalled"):
return 1
return 0
def f():
"*** YOUR CODE HERE ***"
f.beencalled = True
return 0
print(with_if_function())
print(with_if_statement())
在这个例子中,with_if_function
返回 1
,而 with_if_statement
返回 0
,这样就满足了其中一个函数返回数字 1,而另一个不返回的要求。