--- title: "STAT 540 Homework 7" subtitle: "Section 001, Fall 2026  |  **Due: Wednesday, October 28, 2026 (before class)**  |  Total Points: 100" author: "Your Name" date: Oct 21, 2026 date-format: "[Assigned] MMM D, YYYY" format: html: theme: cosmo toc: true toc-depth: 2 code-fold: false highlight-style: github pdf: toc: true execute: echo: true warning: false --- ::: {.callout-important title="📅 Due: Wednesday, October 28, 2026 — before class"} Compile your homework as a webpage (**html**). Then open it in a browser and print it to a **.pdf** file. Upload this pdf file **and** your Quarto (`*.qmd`) file to Blackboard. **Work on the homework independently.** ::: ## Instructions This is the Python counterpart of Homework 3. Everything you need comes from the NumPy and simulation lectures, the *Python Data Science Handbook* (Chapter 2, "Introduction to NumPy"), and *Think Python* (functions and loops). - Write your Python code for each task **and present your results clearly** — a code cell that runs but prints nothing earns no credit. - Every question that asks "what do you observe?" needs a written answer of one to three sentences, not just a plot. - Start every code cell from the setup cell below; later parts reuse objects created in earlier parts. - Use the generator `rng` created below (and its seed) for **all** random numbers, so your results are reproducible and your grader can check them. ```{python} #| label: setup import numpy as np import matplotlib.pyplot as plt from scipy import stats # Use this generator (and this seed) everywhere so your numbers are reproducible. rng = np.random.default_rng(540) ``` --- ## Problem 1. Central limit theorem (20 points) This exercise is for practicing the central limit theorem. ### 1(a) — 10 points Draw $n = 5$ samples from the uniform distribution and calculate the sample mean. Repeat this experiment 200 times, then plot the distribution of the 200 sample means. *Hint:* `rng.uniform(size=n)` draws `n` samples from $U(0,1)$. To draw the density curve, use `scipy.stats.gaussian_kde` — the Python counterpart of R's `plot(density(x))`: ```python kde = stats.gaussian_kde(xbars) grid = np.linspace(xbars.min(), xbars.max(), 200) ax.plot(grid, kde(grid)) ``` Give the plot a title and axis labels. ```{python} #| label: p1a # YOUR CODE HERE ``` ### 1(b) — 3 points Repeat (a) but use $n = 100$. ```{python} #| label: p1b # YOUR CODE HERE ``` ### 1(c) — 7 points Compare the two sampling distributions you obtained in (a) and (b). What do you observe? Report the standard deviation of the sample means in each case and connect what you see to the central limit theorem. > **Your answer:** > > *(write one to three sentences here)* --- ## Problem 2. A function for a sum (6 points) Write a function `compute_s_n(n)` that for any given `n` computes the sum $$S_n = 1^2 + 2^2 + \ldots + n^2 .$$ Report the value of the sum when `n = 10`. ```{python} #| label: p2 def compute_s_n(n): # YOUR CODE HERE pass # YOUR CODE HERE ``` --- ## Problem 3. Simulation and the distribution of p-values (30 points) Perform the following steps in Python. ### 3(a) — 2 points Simulate 30 samples from a Normal distribution with mean 0 and standard deviation 1. *Hint:* `rng.normal` ```{python} #| label: p3a # YOUR CODE HERE ``` ### 3(b) — 6 points Randomly assign 15 of the samples into a **control** group and 15 into a **treatment** group. *Hint:* `rng.permutation` shuffles the values (or the positions `0, 1, ..., 29`); the first 15 can then go to one group and the last 15 to the other. Print both groups so your grader can see the split. ```{python} #| label: p3b # YOUR CODE HERE ``` ### 3(c) — 4 points Perform a two-sample t-test comparing the control and treatment groups, and report the p-value. *Hint:* `scipy.stats.ttest_ind` ```{python} #| label: p3c # YOUR CODE HERE ``` ### 3(d) — 4 points Randomly generate 1000 samples from the uniform distribution and plot a histogram of the 1000 samples. *Hint:* `ax.hist` ```{python} #| label: p3d fig, ax = plt.subplots(figsize=(7, 4)) # YOUR CODE HERE plt.tight_layout() plt.show() ``` ### 3(e) — 14 points Repeat (a), (b) and (c) 1000 times, storing the 1000 p-values in a NumPy array. Plot a histogram of these 1000 p-values. What is the distribution of the p-values? Compare your histogram with the histogram from part (d) and explain, in one or two sentences, why the two look the way they do. ```{python} #| label: p3e # YOUR CODE HERE ``` > **Your answer:** > > *(write one to two sentences here)* --- ## Problem 4. Simulating a DNA sequence (34 points) ### 4(a) — 6 points Simulate a string of 10,000 characters drawn uniformly and independently from the set `{"A", "C", "G", "T"}`. *Hint:* `rng.choice` returns an array of characters; `"".join(array)` turns that array into a single string. ```{python} #| label: p4a # YOUR CODE HERE ``` ### 4(b) — 4 points Create a frequency table of the characters in the string — that is, how many times each of `A`, `C`, `G`, `T` appears. *Hint:* `np.unique(..., return_counts=True)` is the counterpart of R's `table()`. ```{python} #| label: p4b # YOUR CODE HERE ``` ### 4(c) — 24 points Write a function `ktuple_table(s, k)` that creates a contingency table of **adjacent k-tuples**. For example, with `k = 3` and the string `"CAGACAAAAC"` your function should produce | AAA | AAC | ACA | AGA | CAA | CAG | GAC | |:---:|:---:|:---:|:---:|:---:|:---:|:---:| | 2 | 1 | 1 | 1 | 1 | 1 | 1 | The function should return a dictionary whose keys are the k-tuples that actually occur and whose values are their counts. Print the result sorted by k-tuple. ::: {.callout-warning title="Restrictions"} Build each k-tuple using **only `for` loops and `"".join(...)`**. Do **not** use string slicing (`s[i:i+k]`), `collections.Counter`, `re`, `zip`, `itertools`, or `pandas.value_counts`. Counting with a plain dictionary is fine and is the point of the exercise. ::: Test your function on `"CAGACAAAAC"` with `k = 3` (you should reproduce the table above), then apply it to your 10,000-character string from (a) with `k = 3` and report the five most common 3-tuples. ```{python} #| label: p4c def ktuple_table(s, k): # YOUR CODE HERE pass # Test on the small example # YOUR CODE HERE ``` ```{python} #| label: p4c-apply # Apply to the 10,000-character string from (a) and report the top 5 # YOUR CODE HERE ``` --- ## Problem 5. Factorial from scratch (10 points) Recall that $x! = 1 \times 2 \times 3 \times \ldots \times x$ and $0! = 1$, where $x$ is an integer $\ge 0$. Write your own function `my_factorial(x)` to perform this calculation. Your function should return `None` (and print a clear message) if `x` is negative or not an integer. Demonstrate it on `x = 0`, `x = 1`, `x = 5` and `x = 10`. ::: {.callout-warning title="Restrictions"} Do **not** use `math.factorial`, `math.prod`, `np.prod`, or `scipy.special.factorial`. ::: ```{python} #| label: p5 def my_factorial(x): # YOUR CODE HERE pass # YOUR CODE HERE ``` --- ## Before you submit - [ ] Every code cell runs from top to bottom without errors - [ ] Every part prints its result — no silent cells - [ ] Problems 1(c) and 3(e) each have a written answer in your own words - [ ] Every plot has a title and axis labels - [ ] Problem 4(c) uses only `for` loops and `"".join(...)` — no slicing, no `Counter`, no `re` - [ ] Problem 5 does not call any built-in factorial or product function - [ ] You rendered with `quarto render hw7.qmd`, printed the html to pdf, and are uploading **both** the pdf and the `.qmd` **Due: Wednesday, October 28, 2026, before class.**