#9 Stylometry, Monte Carlo, Networks & Monty Hall
Computational Thinking
in Action
A high-yield, interactive Week 9 study guide: understand the core ideas, memorize the Python patterns, revise the formulas, and test yourself with 10 exam-style MCQs.
Week 9 at a glance
Four computational ideas, four practical toolchains.
01 · Sampling & pixels
Monte Carlo estimation, RGB channels, NumPy arrays and PIL images.
02 · Writing fingerprints
Stylometry, Federalist Papers, tokenization and NLTK frequency distributions.
03 · People as networks
Nodes, edges, graph models, shortest paths, NetworkX and Gephi.
04 · Probability in a game
Monty Hall, conditional host behavior, and why swapping wins more often.
Monte Carlo Area Estimation & Image Processing
Estimate what is difficult to measure directly, then represent images as numeric arrays.
Monte Carlo method
A randomized algorithm that estimates a quantity using repeated random samples. For area estimation, scatter points uniformly across a known bounding region and compare how many land in the target.
- Assumption: samples are uniformly distributed across the bounding region.
- Convergence: estimates generally become more stable as sample count increases.
- Exam cue: the ratio of sampled points approximates the ratio of areas.
RGB pixels & coordinates
An image is a grid of pixels. In RGB mode, each pixel has three channels: red, green and blue. Each channel is commonly an unsigned 8-bit integer (uint8).
| Color | RGB tuple |
|---|---|
| Black | (0, 0, 0) |
| White | (255, 255, 255) |
| Orange | (255, 128, 0) |
| Blue | (0, 0, 255) |
Array shape: (height, width, 3). PIL pixel access uses (x, y), while a NumPy image array is indexed as array[row, column, channel] (commonly array[y, x, channel]).
Create a blank image with NumPy + PIL
import numpy as np
from PIL import Image
width = 5
height = 4
array = np.zeros((height, width, 3), dtype=np.uint8)
img = Image.fromarray(array)
img.save("test.png")Creates a black 4-row × 5-column RGB image and saves it as test.png.
Read a pixel with PIL
from PIL import Image
im = Image.open("test1.png")
rgb_im = im.convert("RGB")
r, g, b = rgb_im.getpixel((x, y))Converting to RGB ensures a three-channel tuple for the pixel read.
Monte Carlo workflow: map pixels
import random
count_target = 0
count_bounding = 0
iterations = 100000
for _ in range(iterations):
x = random.randint(0, width - 1)
y = random.randint(0, height - 1)
# Inspect the pixel's channel/color to classify its region.
# Increment the relevant counters.
estimated_area = (count_target / count_bounding) * known_area
scipy.misc.imread() in an example. That API is deprecated/removed in modern SciPy versions; use a current image-reading method such as PIL.Image.open() or imageio.imread() in modern projects. For an exam based strictly on lecture notes, recognize the original function name.NLP & Author Stylometry
Use measurable language patterns to investigate who wrote a text.
Stylometry
Stylometry is the quantitative study of literary style. It assumes that writers may exhibit persistent, partly subconscious patterns that can be measured across texts.
- Word-length frequency distribution
- Sentence-length distribution
- Vocabulary richness
- Punctuation usage
Mendenhall’s Characteristic Curves (1887): compare frequencies of words of different lengths across text segments, such as 5,000-word blocks.
Federalist Papers case study
The 85 essays were published under the pseudonym Publius. Stylometry compares the known-author groups with the disputed essays.
| Group | Count in notes |
|---|---|
| Hamilton (known) | 51 |
| Madison (known) | 14 |
| John Jay (known) | 5 |
| Shared Hamilton & Madison | 3 |
| Disputed essays | 12 |
The notes say the disputed curves track Hamilton and Madison more closely than Jay, whose word-length curve differs at the head and tail.
Tokenize, clean, count
import nltk
nltk.download("all")
tokens = nltk.word_tokenize(raw_text_string)
clean_words = [
token for token in tokens
if any(c.isalpha() for c in token)
]
word_lengths = [len(word) for word in clean_words]
fdist = nltk.FreqDist(word_lengths)
fdist.plot(15, title="Author Signature")How to read the workflow
word_tokenize()splits raw text into tokens.- The filter retains tokens containing at least one alphabetic character.
len()measures token length.FreqDist()counts how often each length occurs.plot(15)plots the first 15 length values.
any(c.isalpha() for c in token), which keeps tokens containing letters; it does not strictly remove every token that also contains punctuation.Network Analysis & Six Degrees of Separation
Model relationships as nodes and edges, then study connectivity and distance.
Graph theory essentials
- Graph:
G = (V, E), with vertices/nodesVand edgesE. - Complete graph: every pair of distinct nodes has an edge.
- Connected graph: a path exists between every pair of nodes.
- Undirected: edges have no orientation; relationships work both ways.
- Directed: edges have a defined direction.
- Shortest path/geodesic: path with the fewest edges, or minimum total weight in a weighted graph.
Random vs scale-free
| Model | Mechanism | Signature |
|---|---|---|
Erdős–Rényi G(n,p) | Each node pair connects with probability p. | Degrees cluster around average; no dominant hubs typically. |
| Barabási–Albert | New nodes attach to m existing nodes by preferential attachment. | Power-law-like degree distribution; a few hubs and many low-degree nodes. |
Preferential attachment: “rich get richer”—high-degree nodes are more likely to attract new links.
Six degrees: a chain of acquaintances averages around six hops in the popular concept. The notes illustrate exponential growth with 100 contacts per person: 100⁶ = 10¹² potential contact paths before accounting for overlap.
NetworkX: create graphs
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_node(1) G.add_nodes_from([1, 2, 3]) G.add_edge(1, 2) G.add_edges_from([(2, 3), (1, 3)]) nx.draw(G) plt.show() G_complete = nx.complete_graph(20) G_random = nx.gnp_random_graph(50, 0.3) G_scalefree = nx.barabasi_albert_graph(50, 2)
Paths & Gephi
# Read an edge list
G = nx.read_edgelist("facebook_combined.txt")
# Shortest path length between nodes u and v
length = nx.shortest_path_length(G, source=u, target=v)
# Export for Gephi
nx.write_gexf(G, "analysis1.gexf")- Edge list: simple text pairs such as
node1 node2. - GEXF: structured XML graph format that can carry attributes and metadata.
- Gephi: interactive visualization, layouts (e.g., Force Atlas), ranking by degree, and statistics.
Network-wide path metrics
nodes = list(G.nodes())
spl_list = []
for u in nodes:
for v in nodes:
if u != v:
spl_list.append(nx.shortest_path_length(G, u, v))
min_spl = min(spl_list)
max_spl = max(spl_list) # diameter for a connected graph
avg_spl = np.average(spl_list)Probability & the Monty Hall Problem
The host’s knowledge and rules change how the reveal should be interpreted.
Game setup
- Three closed doors: one prize, two empty.
- You select one door; its initial chance of hiding the prize is 1/3.
- A host who knows where the prize is opens an unchosen empty door.
- You may stay with the original choice or swap to the other unopened door.
Stay vs swap
| Strategy | Winning condition | Win probability |
|---|---|---|
| Stay | Initial pick was correct. | 1/3 ≈ 33.3% |
| Swap | Initial pick was wrong. | 2/3 ≈ 66.7% |
The initial 2/3 probability that the prize is in the unchosen set is concentrated on the one remaining unopened door because the host deliberately reveals an empty door.
P(swap wins) = 2/3
Quick Revision
Search the key terms, then tap a card to reveal its answer.
Formula & function sheet
| Topic | Formula / function | Purpose / exam cue |
|---|---|---|
| Monte Carlo area | (target dots / bounding dots) × known area | Estimate an irregular area from a known region. |
| Image creation | Image.fromarray(arr) | Convert a NumPy array into a PIL image. |
| Pixel extraction | img.convert("RGB").getpixel((x,y)) | Get the pixel’s RGB tuple. |
| Stylometry | nltk.FreqDist(word_lengths) | Build a word-length frequency distribution. |
| Token cleanup | c.isalpha() | Test whether a character is alphabetic. |
| Graph creation | nx.complete_graph(n) | Create a complete graph. |
| Scale-free graph | nx.barabasi_albert_graph(n, m) | Generate a preferential-attachment graph. |
| Shortest path | nx.shortest_path_length(G, source, target) | Find minimum hop count for an unweighted graph. |
| Monty Hall | P(swap)=2/3; P(stay)=1/3 | Swap wins when the original choice was wrong. |
High-yield exam checklist
- Remember
(height, width, 3)for RGB array shape; distinguish PIL(x,y)from array[row,column]. - Monte Carlo accuracy generally improves with more uniform random samples; it does not guarantee an exact result on each run.
- Stylometry compares feature distributions, not just the topic or meaning of a text.
- Scale-free networks have hubs; preferential attachment explains their emergence.
- Exclude self-pairs when computing pairwise path lengths, and handle disconnected graphs.
- Monty Hall’s 2/3 swap result depends on the standard informed-host rules.
Interactive 10-MCQ Quiz
Choose an option for instant feedback and an explanation. Finish all questions to see your score; retry any time.
Comments
Post a Comment