1

For the following codes (which is used to generate a graph in IPython), what does if k in [0, len(n_trials) - 1] else None do?

%matplotlib inline
from IPython.core.pylabtools import figsize
import numpy as np
from matplotlib import pyplot as plt
#total figure size
figsize(11, 9)

import scipy.stats as stats

dist = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0, 1, 100)

# For the already prepared, I'm using Binomial's conj. prior.
for k, N in enumerate(n_trials):
    sx = plt.subplot(len(n_trials) / 2, 2, k + 1)
    plt.xlabel("$p$, probability of heads") \
        if k in [0, len(n_trials) - 1] else None
    #Make the y label not appeared
    plt.setp(sx.get_yticklabels(), visible=False)
    heads = data[:N].sum()
    y = dist.pdf(x, 1 + heads, 1 + N - heads)
    plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads))
    plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4)
    plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1)

    leg = plt.legend()
    leg.get_frame().set_alpha(0.4)
    plt.autoscale(tight=True)


plt.suptitle("Bayesian updating of posterior probabilities",
             y=1.02,
             fontsize=14)

plt.tight_layout()
william007
  • 13,874
  • 18
  • 76
  • 146

1 Answers1

5

That code is misleading in a number of ways. As pointed out in the comments, the line you're asking about is a continuation of the previous line, because of the escaping backslash. It becomes:

plt.xlabel("$p$, probability of heads") if k in [0, len(n_trials) - 1] else None

Which is just a convoluted way of writing:

if k == 0 or k == len(n_trials) - 1:
    plt.xlabel("$p$, probability of heads")

The syntax 'True' if condition else 'False' is Python's version of the ternary operator, but there is no reason to use it in this case.

Community
  • 1
  • 1
grc
  • 20,175
  • 4
  • 37
  • 63