Reputation: 80
This is a question for a homework problem that I cant figure out:
Question Beginning
Q3. Let's try to write a function that does the same thing as an if statement:
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
This function actually doesn't do the same thing as an if statement in all cases. To prove this fact, write functions c, t, and f such that one of these functions returns the number 1, but the other does not:
def with_if_statement():
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
Question End
Heres what I figured out:
with_if_statement() does not evaluate f() if c() is true, but with_if_function() evaluates all 3 before checking if c() is true or not.
So, I thought of assigning a global variable in c(), and changing its value in f()
heres my code (which does not work):
def c():
try:
global x
except NameError:
x=1
if x==1:
return True
else:
return False
def t():
if x==1:
return (1)
else:
return (0)
def f():
global x
x=2
if x==1:
return (1)
else:
return (0)
can anyone help me figure out the answer? Thanks..!
Upvotes: 4
Views: 6404
Reputation: 901
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())
The question requires that, write 3 functions: c
, t
and f
such that with_if_statement
returns 1
and with_if_function
does not return 1 (and it can do anything else)
At the beginning, the problem seems to be ridiculous since, logically, with_if_statement
and with_if_function
are same. However, if we see these two functions from an interpreter view, they are different.
The function with_if_function
uses a call expression, which guarantees that all of its operand subexpressions will be evaluated before if_function
is applied to the resulting arguments. Therefore, even if c
returns False
, the function t
will be called. By contrast, with_if_statement
will never call t
if c
returns False (This paragraph from the UCB website).
def c():
return True
def t():
return 1
def f():
'1'.sort() # anything breaks the program is OK
Upvotes: 2
Reputation: 993951
The global
statement shouldn't throw a NameError
(and so you won't run x=1
in c()
). I would try rewriting your code without using exceptions, they won't be necessary to solve this and are making it more complicated than it needs to be. Using a global variable and having side effects in your functions is certainly the right track.
Upvotes: 2