GitHub

@@ -313,7 +313,8 @@ function*---as we did above.

313313314314

## Exercises

315315316-

### Exercise 1

316+

```{exercise}

317+

:label: exercise_1

317318318319

Recall that $n!$ is read as "$n$ factorial" and defined as

319320

$n! = n \times (n - 1) \times \cdots \times 2 \times 1$.

@@ -323,17 +324,21 @@ write our own version as an exercise.

323324324325

In particular, write a function `factorial` such that `factorial(n)` returns $n!$

325326

for any positive integer $n$.

327+

```

326328327-

### Exercise 2

329+

```{exercise}

330+

:label: exercise_2

328331329332

The [binomial random variable](https://en.wikipedia.org/wiki/Binomial_distribution) $Y \sim Bin(n, p)$ represents the number of successes in $n$ binary trials, where each trial succeeds with probability $p$.

330333331334

Without any import besides `from numpy.random import uniform`, write a function

332335

`binomial_rv` such that `binomial_rv(n, p)` generates one draw of $Y$.

333336334337

Hint: If $U$ is uniform on $(0, 1)$ and $p \in (0,1)$, then the expression `U < p` evaluates to `True` with probability $p$.

338+

```

335339336-

### Exercise 3

340+

```{exercise}

341+

:label: exercise_3

337342338343

First, write a function that returns one realization of the following random device

339344

@@ -346,12 +351,16 @@ Second, write another function that does the same task except that the second ru

346351

- If a head occurs `k` or more times within this sequence, pay one dollar.

347352348353

Use no import besides `from numpy.random import uniform`.

354+

```

349355350356

## Solutions

351357352-

### Exercise 1

358+

```{solution-start} exercise_1

359+

:label: solution_1

360+

:class: dropdown

353361354362

Here's one solution.

363+

```

355364356365

```{code-cell} python3

357366

def factorial(n):

@@ -363,7 +372,13 @@ def factorial(n):

363372

factorial(4)

364373

```

365374366-

### Exercise 2

375+

```{solution-end}

376+

```

377+378+

```{solution-start} exercise_2

379+

:label: solution_2

380+

:class: dropdown

381+

````

367382368383

```{code-cell} python3

369384

from numpy.random import uniform

@@ -379,9 +394,16 @@ def binomial_rv(n, p):

379394

binomial_rv(10, 0.5)

380395

```

381396382-

### Exercise 3

397+

```{solution-end}

398+

```

399+400+401+

```{solution-start} exercise_3

402+

:label: solution_3

403+

:class: dropdown

383404384405

Here's a function for the first random device.

406+

```

385407386408

```{code-cell} python3

387409

from numpy.random import uniform

@@ -423,3 +445,5 @@ def draw_new(k): # pays if k successes in a sequence

423445

draw_new(3)

424446

```

425447448+

```{solution-end}

449+

```

Read the original on github.com ↗