#9 Stylometry, Monte Carlo, Networks & Monty Hall

NPTEL Joy of Computing — Week 9 Study Guide
The Joy of Computing · Exam prep

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.

4 modulesCode referencesSearchable flashcards10-question quiz

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.

Module 01

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.

Target area ≈ (target samples ÷ bounding-region samples) × bounding-region area
  • 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.
The supplied notes give an illustrative error of about 4,000 km² at 10,000 iterations versus about 1,000–2,000 km² at 100,000 iterations. These are examples, not guarantees.

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

ColorRGB 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]).

Coordinate convention matters: PIL uses (x, y); NumPy indexing uses [row, column, channel]. The pasted notes describe the array dimensions as height × width × 3.

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
The source notes show 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.
Module 02

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.

Signature = distribution of measurable writing features

Federalist Papers case study

The 85 essays were published under the pseudonym Publius. Stylometry compares the known-author groups with the disputed essays.

GroupCount in notes
Hamilton (known)51
Madison (known)14
John Jay (known)5
Shared Hamilton & Madison3
Disputed essays12

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

  1. word_tokenize() splits raw text into tokens.
  2. The filter retains tokens containing at least one alphabetic character.
  3. len() measures token length.
  4. FreqDist() counts how often each length occurs.
  5. plot(15) plots the first 15 length values.
The source’s filter uses any(c.isalpha() for c in token), which keeps tokens containing letters; it does not strictly remove every token that also contains punctuation.
Module 03

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/nodes V and edges E.
  • 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.
Complete graph edges: n(n − 1) / 2

Random vs scale-free

ModelMechanismSignature
Erdős–Rényi G(n,p)Each node pair connects with probability p.Degrees cluster around average; no dominant hubs typically.
Barabási–AlbertNew 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)
This nested loop may count each undirected pair twice. Also, shortest paths are undefined for node pairs in different connected components; analyze connected components or use the appropriate connected subgraph before computing all-pairs metrics.
Module 04

Probability & the Monty Hall Problem

The host’s knowledge and rules change how the reveal should be interpreted.

Game setup

  1. Three closed doors: one prize, two empty.
  2. You select one door; its initial chance of hiding the prize is 1/3.
  3. A host who knows where the prize is opens an unchosen empty door.
  4. You may stay with the original choice or swap to the other unopened door.
Key conditionThe standard result assumes the host always knows where the prize is, always opens an empty unchosen door, and always offers the swap.

Stay vs swap

StrategyWinning conditionWin probability
StayInitial pick was correct.1/3 ≈ 33.3%
SwapInitial 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(stay wins) = 1/3
P(swap wins) = 2/3
It is not automatically 50/50: the host’s reveal is constrained, not a random opening of any door.

Quick Revision

Search the key terms, then tap a card to reveal its answer.

0 cards

Formula & function sheet

TopicFormula / functionPurpose / exam cue
Monte Carlo area(target dots / bounding dots) × known areaEstimate an irregular area from a known region.
Image creationImage.fromarray(arr)Convert a NumPy array into a PIL image.
Pixel extractionimg.convert("RGB").getpixel((x,y))Get the pixel’s RGB tuple.
Stylometrynltk.FreqDist(word_lengths)Build a word-length frequency distribution.
Token cleanupc.isalpha()Test whether a character is alphabetic.
Graph creationnx.complete_graph(n)Create a complete graph.
Scale-free graphnx.barabasi_albert_graph(n, m)Generate a preferential-attachment graph.
Shortest pathnx.shortest_path_length(G, source, target)Find minimum hop count for an unweighted graph.
Monty HallP(swap)=2/3; P(stay)=1/3Swap 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.

Question 1 of 10

NPTEL · The Joy of Computing · Week 9
Prepared from the supplied study notes. The page is self-contained: HTML, CSS and JavaScript are included in this file; no external libraries or network access are required.

Comments

Popular posts from this blog

#11 Calendar Arithmetic & Browser Automation with Selenium

#12 Page Rank & Collatz Conjuncture

#10 NumPy, Flames, Digital images & compression