STAT 540 Homework 7

Section 001, Fall 2026  |  Due: Wednesday, October 28, 2026 (before class)  |  Total Points: 100

Author

Your Name

Published

Assigned Oct 21, 2026

ImportantπŸ“… 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.
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)):

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.

# YOUR CODE HERE

1(b) β€” 3 points

Repeat (a) but use \(n = 100\).

# 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.

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

# 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.

# 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

# 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

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.

# 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.

# 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().

# 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.

WarningRestrictions

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.

def ktuple_table(s, k):
    # YOUR CODE HERE
    pass

# Test on the small example
# YOUR CODE HERE
# 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.

WarningRestrictions

Do not use math.factorial, math.prod, np.prod, or scipy.special.factorial.

def my_factorial(x):
    # YOUR CODE HERE
    pass

# YOUR CODE HERE

Before you submit

Due: Wednesday, October 28, 2026, before class.