'Using Nested Conditional Expressions
I have an exercise from a book with this code snippet:
def binomial_coeff(n, k):
"""Compute the binomial coefficient "n choose k".
n: number of trials
k: number of successes
returns: int
"""
if k == 0:
return 1
if n == 0:
return 0
res = binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1)
return res
the goal of the exercise is to rewrite the if statements as nested conditional expressions. I understand how to write a conditional expression e.g.
return 1 if k == 0
What am I missing here? By doing this nested, I can't seem to figure it out. PyCharm keeps complaining about that it the second part of the code is unreachable.
return 1 if k == 0 else return 0 if n == 0
Solution 1:[1]
return binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1) if k != 0 and n != 0 else (1 if k == 0 else 0)
but seriously: why would you want to do that? That's insanely unreadable.
Solution 2:[2]
def binomial_coeff(n, k):
"""Computes the binomial coefficient "n chose k".
n: number of trials
k: number of successes
returns: int
"""
return 1 if k == 0 else (0 if n == 0 else (binomial_coeff(n - 1, k) + binomial_coeff(n - 1, k - 1)))
bi_memo = {}
def binomial_coeff_memo(n, k):
bi_memo[n, k] = 1 if k == 0 else (0 if n == 0 else (
bi_memo[n, k] if (n, k) in bi_memo else (binomial_coeff_memo(n - 1, k) + binomial_coeff_memo(n - 1, k - 1))))
return bi_memo[n, k]
if __name__ == '__main__':
print(binomial_coeff(8, 3))
print(binomial_coeff_memo(8, 3))
Solution 3:[3]
def binomial_coeff(n, k):
"""Computes the binomial coefficient "n chose k".
n: number of trials
k: number of successes
returns: int
"""
return 1 if k == 0 else 0 if n == 0 else bico(n-1, k) + bico(n-1, k-1)
Solution 4:[4]
A little bit late, but here's my two cents:
return 1 if k == 0 else (0 if n == 0 else binomial_coeff(n - 1, k) + binomial_coeff(n - 1, k - 1))
Explanation:
Conditional expressions can be nested. If the basic syntax is:
return value1 if condition1 else value2
Then, by substituting value2 for another conditional expression (in parenthesis), we get:
return value1 if condition1 else (value2 if condition2 else value3)
which is what is needed to solve the exercise.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | freakish |
Solution 2 | troy |
Solution 3 | Alexbot |
Solution 4 |