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
4 Answers 4
return 1 if k == 0 else (0 if n == 0 else binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1))
but seriously: why would you want to do that? That's insanely unreadable.
3 Comments
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))
1 Comment
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)
2 Comments
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.
1 Comment
Explore related questions
See similar questions with these tags.
if-elif-elseconditional expressions and your doubt about Pycharm complaining, is that the error means any statement after areturnis unreachable in a functionreturns on the same line is actually invalid syntax, so IDK why you're getting a warning about unreachable code.