I ran into this expression in a question here about knapsack problems:
def f(v, i, S):
if i >= len(v): return 1 if S == 0 else 0
count = f(v, i + 1, S)
count += f(v, i + 1, S - v[i])
return count
When I try to write out line two if i >= len(v): return 1 if S == 0 else 0
in a more general form I get an error:
In [3]: if test1 : print x if test2 else print y
File "<ipython-input-3-9d4131fa0c48>", line 1
if test1 : print x if test2 else print y
^
SyntaxError: Missing parentheses in call to 'print'
Here is a generalized form:
In [16]: if True : print("first") if True else print("second")
first
In [17]: if True : print("first") if False else print("second")
second
In [18]: if False : print("first") if True else print("second")
[nothing]
In [19]: if False : print("first") if False else print("second")
[nothing]
What do you call this?
I'm surprised you can just take out the second positive case for if...then...else
and turn it into if...else
.
UPDATE: Sorry bout the python3 noob mistake, I just wasn't paying attention. As noted, the answers don't make sense without the mistake, so I've striked out the erroneous code.