Ludium
Sign In
Introduction to Computational Thinking and Data Science
Optimization
01Optimization Models and the Knapsack Problem02Brute-Force Knapsack and the Exponential Power Set03Greedy Algorithms: One Function, Any Definition of Best04Lambda Keys and Why Greedy Can Miss the OptimumProblem setMIT problem set
01The Knapsack Search Tree: Every Combination, 2ⁿ Nodes02Recursive maxVal: An Exhaustive Search That Beats Greedy03Memoization: Turning Slow Fibonacci into fastFib04Overlapping Subproblems and the Memoized KnapsackProblem setMIT problem set
Graph Models
01Graphs as Models: Nodes, Edges and Euler's Seven Bridges02Coding a Graph in Python: Node, Edge, Digraph and Graph03Depth-First Search for the Shortest Path in a Graph04Breadth-First Search: A Queue of Paths, Fewest Hops FirstProblem setMIT problem set
Stochastic Thinking
01Predictive Nondeterminism and the Stochastic Die Roll02Probability as Counting, and When Multiplying Fails03Simulating Rare Events: Random Seeds and Many Trials04The Birthday Problem: Formula Versus SimulationProblem setMIT problem set
01The Drunkard's Walk: Location, Drunk and Field Classes02Sanity Checks: Catching a Plausible Random-Walk Bug03Plotting Walk Distance: Square Root versus Straight Line04Wormhole Fields: Overriding a Method and Styling PlotsProblem setMIT problem set
01Monte Carlo Simulation: Populations, Samples and Trust02Simulating Roulette and the Law of Large Numbers03The Gambler's Fallacy and Regression to the Mean04The House Edge, Variance and Standard Deviation05Confidence Intervals for a Roulette Simulation06The Normal Curve, PDFs and the Empirical RuleProblem setMIT problem set

Wormhole Fields: Overriding a Method and Styling Plots

How does overriding one method of Field add wormholes, and why should plot styles be set once rather than in every call?


Finger exercises

Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.

0 / 5 passed
Exercise 1 of 5

A field subclass with wormholes

Location and Field are given. Define HoleField(Field) whose __init__(self, holes) takes a list of pairs ((x, y), (newX, newY)): initialise the field the usual way, then store in self.wormholes a dictionary mapping each (x, y) to Location(newX, newY).

Given code — runs before yours
import random

class Location(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, deltaX, deltaY):
        return Location(self.x + deltaX, self.y + deltaY)

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def distFrom(self, other):
        xDist = self.x - other.getX()
        yDist = self.y - other.getY()
        return (xDist**2 + yDist**2)**0.5

    def __str__(self):
        return '<' + str(self.x) + ', ' + str(self.y) + '>'


class Drunk(object):
    def __init__(self, name=None):
        self.name = name

    def __str__(self):
        if self.name != None:
            return self.name
        return 'Anonymous'


class UsualDrunk(Drunk):
    def takeStep(self):
        stepChoices = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        return random.choice(stepChoices)


class Field(object):
    def __init__(self):
        self.drunks = {}

    def addDrunk(self, drunk, loc):
        if drunk in self.drunks:
            raise ValueError('Duplicate drunk')
        else:
            self.drunks[drunk] = loc

    def getLoc(self, drunk):
        if drunk not in self.drunks:
            raise ValueError('Drunk not in field')
        return self.drunks[drunk]

    def moveDrunk(self, drunk):
        if drunk not in self.drunks:
            raise ValueError('Drunk not in field')
        xDist, yDist = drunk.takeStep()
        self.drunks[drunk] = self.drunks[drunk].move(xDist, yDist)
1
2
3
4
5
class HoleField(Field):
    def __init__(self, holes):
        ...  # your code here

Scratchpad— run any Python to test ideas
1
2
3
4
5
# Scratchpad — run any Python here to test ideas.
# Anything you write below stays separate from the problem's tests.

print("hello, world")

Python runtime ready in a moment
Python runs in your browser
⌘/Ctrl + Enter runs the checks
?
is a Field with no drunks yet
?
maps each hole to a Location
←Previous Plotting Walk Distance: Square Root versus Straight LineNext Monte Carlo Simulation: Populations, Samples and Trust →