afettouhi
afettouhi

Reputation: 75

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

Upvotes: 0

Views: 853

Answers (4)

freakish
freakish

Reputation: 56467

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.

Upvotes: 3

jethro34
jethro34

Reputation: 1

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.

Upvotes: 0

Alexbot
Alexbot

Reputation: 1

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)

Upvotes: 0

troy
troy

Reputation: 1

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))

Upvotes: 0

Related Questions