Exercise 11.1 (Masa)


In [ ]:

Exercise 11.2 (Wendy)


In [ ]:

Exercise 11.3 (Dan)


In [3]:
def histogram(s):
    d = dict()
    for c in s:
        d[c] = d.get(c, 0) + 1
    return d

In [4]:
def print_hist(h):
    keys = sorted(h.keys())
    for c in keys:
        print c, h[c]

In [5]:
h = histogram('parrot')
print_hist(h)


a 1
o 1
p 1
r 2
t 1

Exercise 11.4 (Sarah)


In [3]:
#The original functions:
def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

def reverse_lookup(d,v):
    for k in d:
        if d[k] ==v:
            return k
    raise ValueError, 'value does not appear in the dictionary'

h = histogram('easter')
k = reverse_lookup(h,2)  
#this tells you the letters that appear  more twice, but only the first one 
print k


e

my new updated function:


In [4]:
def reverse_lookup2(d,v):
    reverse = dict()
    for k in d:
        value = d[k]
        if value not in reverse and value == v:
            reverse[value] = [k]
        if value in reverse:
            reverse[value].append(k)
    return reverse

In [5]:
h = histogram('easters')
k = reverse_lookup2(h,2)
k


Out[5]:
{2: ['s', 's', 'e']}

Exercise 11.5 (Sarah)

Original function:


In [6]:
#this is the original function from the text
def invert_dict1(d):
    inverse = dict()
    for key in d:
        val = d[key]
        if val not in inverse:
            inverse[val] = [key]
        else:
            inverse[val].append(key)
    return inverse
hist = histogram('parrot')
print hist


{'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}

In [7]:
#and the output of that function
inverse = invert_dict1(hist)
print inverse


{1: ['a', 'p', 't', 'o'], 2: ['r']}

My updated solution:


In [9]:
def invert_dict2(d):
    inverse = dict()
    for key, val in d.iteritems():
        inverse.setdefault(val,[]).append(key)
    return inverse

In [10]:
invert_dict2(hist)


Out[10]:
{1: ['a', 'p', 't', 'o'], 2: ['r']}

In [ ]:
#compare to answer from green tree press - there is an extra bit at the bottom
"""This module contains code from
Think Python by Allen B. Downey
http://thinkpython.com

Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html

"""

def invert_dict(d):
    """Inverts a dictionary, returning a map from val to a list of keys.

    If the mapping key->val appears in d, then in the new dictionary
    val maps to a list that includes key.

    d: dict

    Returns: dict
    """
    inverse = {}
    for key, val in d.iteritems():
        inverse.setdefault(val, []).append(key)
    return inverse


if __name__ == '__main__':
    d = dict(a=1, b=2, c=3, z=1)
    inverse = invert_dict(d)
    for val, keys in inverse.iteritems():
        print val, keys

Exercise 11.6 (Liu)


In [1]:
## solution for 11.6, enjoy
import time

known = {0:0, 1:1}
def fibonacci_new(n):
    if n in known:
        return known[n]
    res = fibonacci_new(n-1) + fibonacci_new(n-2)
    known[n] = res
    return res

def fibonacci_ori(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fibonacci_ori(n-1) + fibonacci_ori(n-2)

# test the original one
start_time = time.time()
print fibonacci_ori(20)
print("--- %s seconds for the ori_one ---" % (time.time() - start_time))

start_time = time.time()
print fibonacci_new(20)
print("--- %s seconds for the new_one ---" % (time.time() - start_time))


6765
--- 0.00876784324646 seconds for the ori_one ---
6765
--- 0.000198841094971 seconds for the new_one ---

Exercise 11.7 (Wendy)


In [ ]:

Exercise 11.9 (Masa)


In [ ]:

Exercise 11.10 (Dan)


In [7]:
def words_to_dict():
    D = {}
    with open('words.txt') as f:
        for word in f:
            D[word.strip().lower()] = True
    return D

def rotate_word(word, r):
    return word[r:] + word[0:r]

def find_word_pairs(D):
    for k in D:
        for r in range(1,len(k)):
            rw = rotate_word(k, r)
            if rw in D:
                print k, rw

In [8]:
D = words_to_dict()

In [9]:
find_word_pairs(D)


scutter cutters
kids skid
stern terns
stere ester
eeliest steelie
it ti
purges spurge
trollers stroller
lots slot
spit pits
spic pics
spin pins
has ash
haw wha
raped drape
spathose pathoses
litre relit
skilling killings
tarsal altars
spurge purges
sonar arson
hames shame
surger urgers
nigglers sniggler
emes seme
tallymen mentally
single ingles
otto toot
wane anew
sump umps
mensa amens
wans swan
glean angle
peculates speculate
trips strip
fishbone bonefish
sane anes
leis isle
terra rater
bedlam lambed
noma mano
pectins inspect
traps strap
incase casein
tzetze tzetze
speer peers
carpers scarper
tiffs stiff
alumin lumina
ire rei
stuff tuffs
marts smart
lappers slapper
swindling windlings
tickles stickle
coopers scooper
petri tripe
puds spud
spontoon pontoons
elbow bowel
carriers scarrier
slimmer limmers
jackboot bootjack
trainers strainer
sprig prigs
supper uppers
wops swop
parks spark
sedile ediles
ragtag tagrag
kittles skittle
peels speel
gallnut nutgall
sending endings
crawlers scrawler
slough loughs
soke okes
chit itch
chin inch
stilt tilts
stile tiles
yeas easy
stroll trolls
smasher mashers
hoes shoe
sparable parables
heughs sheugh
dite edit
dita adit
output putout
housework workhouse
cores score
emus muse
ingroup rouping
smerk merks
swop wops
peises speise
tickings sticking
mites smite
dogwatch watchdog
basal albas
arks sark
astern sterna
stalker talkers
parges sparge
chowchow chowchow
sombre ombres
informal formalin
lips slip
spudding puddings
smiler milers
sheave heaves
links slink
nark knar
ires sire
ired dire
scoop coops
prays spray
scoot coots
wells swell
oast stoa
parkings sparking
times stime
crams scram
secco cosec
peelings speeling
versal salver
ablest stable
ablest tables
booboo booboo
foin info
shunt hunts
smugger muggers
swab wabs
swat wats
swap waps
sway ways
mel elm
shay hays
shackle hackles
ester stere
sham hams
aide idea
aids said
tossup uptoss
sprinter printers
cans scan
zoa azo
ells sell
carts scart
bulbul bulbul
balata atabal
landers slander
swoop woops
boa abo
mocks smock
ajar raja
squad quads
angst stang
angst tangs
shave haves
stang tangs
stang angst
miles smile
sear ears
sear arse
menad admen
wains swain
lave vela
sullage ullages
toners stoner
spica picas
spica aspic
spat pats
pipal palpi
lues slue
alme meal
outwork workout
ervil viler
ombers somber
tacks stack
halts shalt
woodbox boxwood
baal alba
starrier tarriers
too oot
outwatch watchout
roved drove
seating eatings
aggers sagger
spunkie punkies
pecks speck
havens shaven
hakes shake
shodden hoddens
hight thigh
electors selector
wormwood woodworm
sloes loess
swither withers
teams steam
tripe petri
equal quale
tumbles stumble
furfur furfur
tricks strick
ramble ambler
canners scanner
windup upwind
prats sprat
mokes smoke
leaves sleave
prints sprint
backout outback
amin mina
beebee beebee
pullout outpull
amir rami
uppings supping
den end
sand ands
cowls scowl
lighters slighter
sidehill hillside
elm mel
tripes ripest
tripes stripe
peaks speak
dada dada
abet beta
aha aah
creamers screamer
stuck tucks
testes testes
tanks stank
prep repp
ands sand
eighth height
inners sinner
hanks shank
eagle aglee
froufrou froufrou
crews screw
icon coni
pores spore
rundlet trundle
spacer pacers
slaughter laughters
relit litre
smaze mazes
steeve vestee
sun uns
sup ups
abator rabato
parings sparing
alines saline
loops sloop
nome omen
nome meno
store tores
kins skin
viler ervil
stye tyes
shire hires
pates spate
shaugh haughs
smitten mittens
uphold holdup
staler talers
hards shard
perms sperm
edit dite
witchings switching
he eh
wee ewe
heathens ensheath
emoter remote
kidders skidder
pasta tapas
paste tepas
pike kepi
outset setout
avers saver
remet metre
scoffer coffers
swing wings
wots swot
enrich richen
ups sup
waddles swaddle
shopper hoppers
hays shay
outdrop dropout
capes scape
meno nome
meno omen
lenders slender
score cores
sera eras
sera rase
chili lichi
wives swive
stowage towages
speeling peelings
sniffer niffers
oles sole
dangle angled
inhere herein
yarrow arrowy
nester ternes
spay pays
atlatl atlatl
spar pars
spas pass
shive hives
espy pyes
parers sparer
costa tacos
trains strain
lane elan
aa aa
oho ooh
ad da
ah ha
am ma
an na
at ta
ay ya
shaul hauls
coots scoot
standup upstand
ranter errant
sender enders
strolling trollings
siestas tassies
evolver revolve
evolved devolve
stater taters
omental lomenta
haughs shaugh
sinning innings
sparker parkers
slipper lippers
gratin rating
ser ers
sen ens
sel els
knar nark
scamp camps
packman manpack
simp imps
send ends
dentin indent
stakeout takeouts
hents shent
stow tows
stop tops
adders sadder
kiss skis
spile piles
stickler ticklers
straining trainings
tintings stinting
soak oaks
soar oars
troche rochet
thigh hight
stumbling tumblings
scram crams
ediles sedile
acyl lacy
playdown downplay
pathoses spathose
sharper harpers
smoke mokes
piers spier
scamping campings
lackers slacker
dace aced
winks swink
ticks stick
twos wost
tucks stuck
opt top
kepi pike
towages stowage
throw rowth
lyre rely
stinting tintings
grugru grugru
shoe hoes
selves vessel
em me
eh he
er re
space paces
spavin pavins
sunset unsets
sheugh heughs
pilings spiling
scot cots
wounds swound
ship hips
slugger luggers
hacks shack
agers sager
shaw haws
alvine vineal
skis kiss
vera rave
vera aver
snipper nippers
asp spa
asp pas
ask kas
ash has
shotgun gunshot
trees reest
anon nona
else seel
else eels
shat hats
shag hags
shah hahs
user ruse
corers scorer
lumbers slumber
strapper trappers
trines estrin
educes seduce
swaddle waddles
pools spool
ecu cue
babka kabab
staking takings
waps swap
sparer parers
tumblings stumbling
owns sown
griskin risking
ripest stripe
ripest tripes
copulas scopula
dree reed
tela late
ism mis
pelters spelter
stoa oast
braze zebra
near earn
anchor rancho
is si
egal gale
sate ates
pinners spinner
holdup uphold
egest geste
stalk talks
scrawl crawls
skip kips
skit kits
skin kins
skid kids
ere ree
chemical alchemic
pins spin
tapas pasta
cuts scut
shatter hatters
ensheath heathens
aloof loofa
ickers sicker
stinker tinkers
seggar eggars
arts tsar
those ethos
same mesa
samp amps
sinter inters
shallower hallowers
remote emoter
sadist tsadis
nona anon
prigs sprig
spall palls
setback backset
sodium odiums
tokes stoke
ides side
inkers sinker
seduction eductions
koa oak
selector electors
offhand handoff
onset seton
hillside sidehill
stowaway towaways
saline alines
ingrain raining
itch chit
matters smatter
pea ape
tilts stilt
uptoss tossup
ternes nester
trap rapt
sip psi
slipping lippings
rei ire
ree ere
tassies siestas
spryer pryers
slack lacks
tangs angst
tangs stang
stamper tampers
assignor signoras
escot cotes
agas saga
agar raga
eductions seduction
swig wigs
raved drave
testa state
testa tates
snapper nappers
revolve evolver
pats spat
me em
ma am
end den
ens sen
sprinting printings
enter rente
cants scant
mothers smother
goa ago
tsktsk tsktsk
toon onto
shell hells
peers speer
stool tools
hadji jihad
pinking kingpin
ich chi
ich hic
punkies spunkie
mazes smaze
slogan logans
lags slag
heat eath
hear rhea
adore oread
coattail tailcoat
molts smolt
tows stow
spale pales
stroke trokes
pillages spillage
scute cutes
hug ugh
ament menta
muumuu muumuu
cullers sculler
tailcoat coattail
shearer hearers
on no
oh ho
od do
ow wo
os so
strick tricks
idea aide
signore ignores
ebon bone
overturn turnover
rato tora
sticking tickings
malls small
martens smarten
tsar arts
sloop loops
inch chin
wages swage
kips skip
woops swoop
tars star
sliver livers
hags shag
urgers surger
tampers stamper
juju juju
shent hents
stalking talkings
workhouse housework
potters spotter
kris risk
oars soar
scunner cunners
swive wives
izars sizar
regale galere
swear wears
topers stoper
shallow hallows
hearings shearing
enows owsen
still tills
wagers swager
respect spectre
hunters shunter
atabal balata
stable tables
stable ablest
were ewer
saddle addles
owl low
own now
shank hanks
swashing washings
raining ingrain
eagre agree
slate tesla
tref reft
cams scam
spend pends
denounce enounced
squill quills
sod ods
sop ops
sunroof unroofs
scar cars
stole toles
si is
toro roto
oped dope
open nope
ers ser
laws slaw
mane nema
mano noma
stouter touters
esprit sprite
het eth
het the
hes she
ughs sugh
headpin pinhead
speculate peculates
swager wagers
signoras assignor
stung tungs
alert taler
orbs sorb
senate enates
sprint prints
slubber lubbers
shall halls
shalt halts
oils soil
un nu
parses sparse
parsec secpar
olds sold
holed dhole
melts smelt
sexist exists
keens skeen
slid lids
slip lips
oping pingo
hangover overhang
ends send
artal talar
sanger angers
spail pails
slagging laggings
outbreak breakout
cedar arced
weepers sweeper
toccatas stoccata
assess sasses
pedro roped
rancho anchor
torques questor
horns shorn
adit dita
hockers shocker
sparse parses
trippings stripping
vela lave
wo ow
slighting lightings
rifest strife
slashing lashings
crags scrag
congas gascon
tints stint
anes sane
cosec secco
anew wane
nutgall gallnut
loyal alloy
killings skilling
cutes scute
car arc
bonefish fishbone
cars scar
punks spunk
drove roved
slighter lighters
smell mells
upbuild buildup
tews stew
selective electives
laves slave
muleta amulet
pawns spawn
alba baal
sneap neaps
spectre respect
ripost tripos
words sword
stopper toppers
hales shale
hips ship
hews shew
vessel selves
casaba abacas
readd dread
terras raster
lingers slinger
stew tews
ache each
tui uit
hares share
shackler hacklers
ameer ramee
lopers sloper
oughts sought
illy yill
ills sill
rase sera
rase eras
spray prays
sark arks
yap pya
yar rya
kingpin pinking
sprat prats
heathers sheather
latria atrial
smarten martens
mitre remit
kegs skeg
dere rede
sidler idlers
hooters shooter
quale equal
somber ombers
wallows swallow
nave vena
upwind windup
sone ones
mina amin
sinker inkers
idol lido
spiling pilings
kin ink
inters sinter
eked deke
snare nares
pileup uppile
cunners scunner
burnout outburn
item emit
item mite
dodo dodo
squid quids
ays say
mar arm
scarrier carriers
tali alit
weets sweet
arrowy yarrow
switching witchings
shop hops
shot hots
shod hods
grin ring
cabs scab
carps scarp
escar scare
escar cares
talers staler
show hows
sniggle niggles
smoulder moulders
drake raked
rogued drogue
muggers smugger
wost twos
pars spar
idles sidle
toot otto
silk ilks
scuttle cuttles
spa pas
spa asp
lashers slasher
wags swag
semi mise
seme emes
chares eschar
prisere reprise
pails spail
sharpie harpies
galere regale
linecut cutline
alit tali
lams slam
nips snip
geed edge
spelt pelts
questor torques
stub tubs
stun tuns
sugh ughs
smolder molders
riptide tiderip
swot wots
lobo obol
lobo bolo
lobs slob
patters spatter
swallow wallows
spitting pittings
wye yew
roped pedro
scouter couters
scares caress
ambos sambo
takeouts stakeout
coffers scoffer
each ache
aspire spirea
onto toon
quints squint
shipmate mateship
sage ages
orts sort
sprite esprit
slicking lickings
trashes rashest
upturn turnup
huns shun
plum lump
trusties rustiest
pyes espy
hams sham
enol leno
pittings spitting
peds sped
merks smerk
standout outstand
scoff coffs
name amen
swine wines
swink winks
escars carses
sweep weeps
cops scop
ideas aside
inks sink
ables sable
nooks snook
eaters seater
tsadis sadist
risking griskin
rose eros
kills skill
gascon congas
stank tanks
ale lea
alb bal
ala aal
alp pal
cruse ecrus
tags stag
raked drake
obol bolo
obol lobo
quires squire
wats swat
shade hades
turnover overturn
scow cows
scop cops
pram ramp
rating gratin
oaves soave
leavings sleaving
roto toro
rota taro
screed creeds
hooks shook
spillage pillages
sanga angas
sit its
shearing hearings
angle glean
telega legate
eses eses
trays stray
helves shelve
rustiest trusties
star tars
parkers sparker
mateship shipmate
tipples stipple
swan wans
longhead headlong
how who
hot tho
uppers supper
prattles sprattle
snail nails
touters stouter
sellout outsell
enders sender
backset setback
corns scorn
saga agas
pits spit
cats scat
tuns stun
atrial latria
ilka kail
easy yeas
east teas
ilks silk
manpack packman
nickers snicker
smelt melts
soot oots
rente enter
ordo door
goer ergo
sawn awns
strain trains
missal salmis
englut gluten
loggers slogger
plea leap
keets skeet
eviler revile
sall alls
sale ales
macks smack
salp alps
salt alts
slot lots
slow lows
slop lops
slob lobs
slander landers
spare pares
spark parks
pacers spacer
spunk punks
liers slier
slime limes
hades shade
scrape crapes
scamper campers
searing earings
slender lenders
washings swashing
tours stour
smile miles
amens mensa
shuck hucks
wat twa
spriest priests
talar artal
algor goral
nares snare
rived drive
sin ins
stack tacks
taro rota
ago goa
this hist
ods sod
thin hint
coops scoop
slogging loggings
overfly flyover
cuds scud
wares sware
swisher wishers
salver versal
shut huts
shun huns
canters scanter
scart carts
scare cares
scare escar
tabor abort
haves shave
printers sprinter
wears swear
eta tae
eth the
eth het
stumbler tumblers
cuscus cuscus
swiller willers
educed deduce
teles stele
hoots shoot
eon one
saver avers
endings sending
erring ringer
bookcase casebook
struck trucks
scarp carps
sever verse
scrap craps
sprattle prattles
angas sanga
louse ousel
shew hews
liefer ferlie
reest trees
lulu lulu
phase ephas
crapes scrape
steak teaks
steal teals
steam teams
spear pears
spean peans
speak peaks
save aves
sting tings
stint tints
snub nubs
neve even
altars tarsal
nevi vine
editions sedition
enlist listen
troupe roupet
stoccata toccatas
couscous couscous
nema mane
hackles shackle
demote emoted
skite kites
twa wat
outfall fallout
skeg kegs
two wot
melters smelter
watchout outwatch
strainer trainers
stiller tillers
scanner canners
innings sinning
scarping carpings
litters slitter
wigs swig
carses escars
mise semi
swarm warms
bucksaw sawbuck
naps snap
sheuch heuchs
parables sparable
reed dree
reef free
info foin
spike pikes
sniggler nigglers
shone hones
evoker revoke
rove over
stripper trippers
souter outers
wines swine
wined dwine
dhole holed
tabs stab
tabu abut
awl law
pya yap
overall allover
state tates
state testa
ankh khan
ankh hank
mither hermit
toppings stopping
dwine wined
touts stout
even neve
hones shone
strow trows
windlings swindling
keps skep
tye yet
cancan cancan
baa aba
bal alb
spur purs
serai raise
ordines sordine
scopula copulas
beta abet
sizar izars
sego egos
overrun runover
limes slime
augers sauger
alts salt
malar alarm
sour ours
ewers sewer
priers sprier
spier piers
riffing griffin
law awl
lugs slug
lichi chili
leets sleet
ether there
hoke okeh
slum lums
strickle trickles
skeen keens
bedim imbed
cilia iliac
iliac cilia
lakes slake
readout outread
eats seat
eath heat
sprang prangs
cups scup
putout output
pawpaw pawpaw
vine nevi
raise serai
seduce educes
rabato abator
kites skite
uppile pileup
piles spile
outwash washout
leno enol
shock hocks
mews smew
united dunite
midi imid
outburn burnout
lippings slipping
nags snag
pinhead headpin
exists sexist
tailspin pintails
owsen enows
angled dangle
strident tridents
risk kris
withers swither
twas wast
oleins insole
pokes spoke
over rove
terns stern
ingraft rafting
ergo goer
talkers stalker
kaka kaka
outstand standout
splasher plashers
trio riot
cedi dice
cedi iced
snip nips
snit nits
hovels shovel
drogue rogued
kits skit
ritter territ
windled dwindle
tarts start
sculler cullers
ways sway
waggers swagger
formalin informal
haws shaw
isle leis
hermit mither
stake takes
hins shin
hint thin
tarot ottar
deduce educed
stope topes
stope estop
scorer corers
menta ament
lacy acyl
far arf
scowling cowlings
stick ticks
eluded delude
strapping trappings
etas seta
narks snark
blowfly flyblow
hip phi
hic ich
hic chi
edge geed
earings searing
purs spur
cutters scutter
emoted demote
tutu tutu
scrapper crappers
shover hovers
abort tabor
rapt trap
rape aper
deave eaved
richen enrich
ones sone
huts shut
perdu duper
lear earl
mite item
mite emit
slue lues
smote motes
snib nibs
sherd herds
pate tepa
scold colds
kelters skelter
smirk mirks
stripe tripes
stripe ripest
soave oaves
screak creaks
scream creams
shunting huntings
alchemic chemical
overhold holdover
eggars seggar
tame meta
azo zoa
trollings strolling
hucks shuck
choice echoic
chillers schiller
dumdum dumdum
setout outset
slog logs
gunshot shotgun
one eon
ons son
cuffless scuffles
herds sherd
evens seven
elan lane
monde demon
ferlie liefer
smelter melters
edges sedge
rumbled drumble
ruse user
putters sputter
wards sward
albas basal
dyed eddy
seat eats
ottar tarot
smalt malts
small malls
pass spas
strew trews
slope lopes
door ordo
isbas basis
sauger augers
aver vera
aver rave
aves save
sell ells
arson sonar
ugh hug
sitar tarsi
cuffs scuff
spine pines
pingo oping
chi hic
chi ich
span pans
char arch
scanter canters
hauls shaul
pales spale
muts smut
watchdog dogwatch
scent cents
slitter litters
swarmer warmers
splatter platters
supping uppings
toolings stooling
kelps skelp
hearers shearer
greegree greegree
arch char
cullions scullion
eels else
eels seel
coni icon
hank ankh
hank khan
hant than
asking gaskin
sparing parings
stumble tumbles
luffs sluff
layers slayer
oaks soak
now own
ring grin
peans spean
sprier priers
stain tains
slogger loggers
goral algor
scut cuts
scup cups
scud cuds
verse sever
psi sip
larva arval
amp pam
moulders smoulder
sadder adders
outlook lookout
stare tares
start tarts
swagger waggers
sheath heaths
anal alan
ails sail
sleaving leavings
holdover overhold
devolve evolved
pends spend
tiderip riptide
electives selective
lippers slipper
mittens smitten
turnout outturn
craps scrap
warts swart
bowel elbow
hires shire
caracara caracara
poons spoon
eel lee
vesta stave
cones scone
buildup upbuild
stour tours
stout touts
huntings shunting
lids slid
sort orts
talkings stalking
trucks struck
tora rato
hits shit
wiggings swigging
swasher washers
huntsman manhunts
handoff offhand
swipe wipes
staw taws
stag tags
stab tabs
miters smiter
vineal alvine
rafting ingraft
colds scold
egos sego
opes peso
loess sloes
harpies sharpie
skink kinks
sluff luffs
earl lear
earn near
ears arse
ears sear
slasher lashers
basis isbas
downplay playdown
topes estop
topes stope
seven evens
yea aye
kinks skink
yep pye
yet tye
yew wye
platters splatter
ores sore
stripping trippings
scowl cowls
revoke evoker
shoer hoers
logans slogan
varna navar
memo mome
awns sawn
awny yawn
uta tau
spang pangs
strait traits
creaks screak
pepo pope
strip trips
outtake takeout
ramee ameer
elated delate
flyover overfly
elater relate
layover overlay
tyes stye
tsadi adits
withes swithe
trolls stroll
thae haet
debar barde
debar ardeb
elections selection
cue ecu
carers scarer
epic pice
casein incase
snook nooks
speise peises
admen menad
shaddock haddocks
makar karma
pangs spang
angers sanger
stone tones
scant cants
hotshots hotshots
lunks slunk
ought tough
scullion cullions
quills squill
ingles single
drumble rumbled
lums slum
lump plum
harpings sharping
ales sale
nits snit
toppers stopper
mestee esteem
towaways stowaway
tactic tictac
smolt molts
scurf curfs
coffs scoff
nigglings sniggling
scam cams
scan cans
scab cabs
scad cads
etapes peseta
fallout outfall
porters sporter
wabs swab
luggers slugger
spatter patters
sinner inners
enates senate
cuppers scupper
there ether
verser server
nides snide
navar varna
mire emir
hoppers shopper
salter alters
okay kayo
shorn horns
harpers sharper
amass massa
cots scot
tinkers stinker
sweet weets
demon monde
stickle tickles
scrawler crawlers
heaths sheath
manatee emanate
range anger
sepic epics
collops scollop
vole levo
apt tap
ape pea
chichi chichi
grigri grigri
oud udo
stooling toolings
rashest trashes
son ons
takeover overtake
heuchs sheuch
tho hot
shocker hockers
squint quints
wast twas
listen enlist
ink kin
ecrus cruse
outlay layout
parsers sparser
warmers swarmer
lumina alumin
lightings slighting
tares stare
bootjack jackboot
windles swindle
tops stop
ewer were
surd urds
loggings slogging
drabble rabbled
halls shall
lays slay
raja ajar
teas east
reprise prisere
spot pots
stroy troys
slump lumps
skier kiers
tubs stub
echoic choice
scupper cuppers
pics spic
pice epic
skipper kippers
slay lays
takings staking
telemen element
nope open
skittle kittles
slag lags
recent centre
swinger wingers
imps simp
hives shive
hells shell
lea ale
lee eel
wayside sideway
slit lits
teals steal
alloy loyal
rollout outroll
shaven havens
gaskin asking
wingless swingles
ripe peri
pavins spavin
phi hip
vale leva
meta tame
slather lathers
loughs slough
swound wounds
do od
da ad
tains stain
snigger niggers
the het
the eth
hills shill
skelter kelters
pays spay
tesla slate
tipplers stippler
tartar tartar
sniggling nigglings
lakers slaker
anger range
wingers swinger
mense semen
sedition editions
soil oils
hent then
mentally tallymen
speel peels
raga agar
rage ager
stoke tokes
lathers slather
spawner pawners
hogs shog
lacks slack
lomenta omental
smock mocks
dire ired
scouth couths
eddy dyed
kippers skipper
corgi orgic
wot two
swelter welters
herein inhere
els sel
strife rifest
wha haw
titi titi
breakout outbreak
tills still
urges surge
campers scamper
mode demo
route outer
nippers snipper
prayers sprayer
sole oles
aspic spica
aspic picas
snicker nickers
ho oh
ha ah
swingles wingless
taters stater
alpine pineal
washout outwash
sarsar sarsar
spew pews
speck pecks
aural laura
smut muts
smug mugs
scrag crags
arced cedar
romp prom
swag wags
ops sop
shammer hammers
daddle addled
hewers shewer
shin hins
tictac tactic
shit hits
laura aural
slake lakes
bonbon bonbon
thru ruth
ooh oho
oot too
orgic corgi
gelatin elating
spiker pikers
scanning cannings
lopes slope
couths scouth
salmis missal
talks stalk
slumber lumbers
del eld
wails swail
alps salp
lats slat
late tela
scorner corners
loofa aloof
mama mama
crappers scrapper
ate tea
ate eat
wills swill
dwindle windled
smother mothers
cents scent
taces cesta
hows show
urds surd
pares spare
abacas casaba
stroller trollers
eatings seating
lickings slicking
pots spot
washers swasher
verso overs
stagger taggers
strove troves
sharping harpings
overslip slipover
slight lights
priests spriest
cions scion
hats shat
shoot hoots
hallowers shallower
shook hooks
sought oughts
scion cions
mesa same
spout pouts
tridents strident
passover overpass
abo boa
couters scouter
swill wills
elating gelatin
who how
outcook cookout
rely lyre
aper rape
reenter terreen
no on
na an
nu un
smew mews
ombres sombre
lowers slower
sheller hellers
sawbuck bucksaw
sedge edges
arf far
riot trio
outsell sellout
sharp harps
downcome comedown
lavalava lavalava
raster terras
ant tan
manhunts huntsman
shaft hafts
tores store
sparser parsers
tea eat
tea ate
epics sepic
erugos rugose
scuffles cuffless
slave laves
sward wards
sware wares
stoner toners
limmers slimmer
pawners spawner
ages sage
dropout outdrop
rugose erugos
sleave leaves
sore ores
sorb orbs
tiles stile
overtake takeover
trows strow
stipple tipples
cannings scanning
sire ires
lops slop
mugs smug
spun puns
spud puds
willers swiller
alters salter
nicks snick
skelp kelps
pouts spout
niffers sniffer
tinges ingest
seta etas
sputter putters
spoon poons
laughters slaughter
shelve helves
re er
smart marts
runover overrun
mogs smog
layout outlay
zebra braze
toles stole
snap naps
slam lams
hacklers shackler
skep keps
spate pates
copes scope
scope copes
lido idol
spouter pouters
amulet muleta
errant ranter
sport ports
massa amass
drive rived
sable ables
ardeb debar
ardeb barde
snark narks
sloper lopers
ti it
ta at
largo argol
pears spear
scat cats
crimps scrimp
turndown downturn
slowdown lowdowns
sicker ickers
cowlings scowling
aal ala
aah aha
caress scares
curfs scurf
tarsi sitar
swart warts
scape capes
grownup upgrown
eve vee
outturn turnout
tumps stump
element telemen
swail wails
swain wains
ringer erring
tackers stacker
tickers sticker
scorn corns
spinner pinners
slinger lingers
cesta taces
slayer layers
screamer creamers
ins sin
yill illy
sped peds
pikers spiker
scull culls
rabbled drabble
logs slog
shunter hunters
picas aspic
picas spica
seater eaters
territ ritter
headlong longhead
taggers stagger
pose epos
takes stake
hocks shock
tumblers stumbler
emir mire
emit mite
emit item
paces space
heart earth
hears shear
shooter hooters
trumpets strumpet
pills spill
havers shaver
mells smell
slaker lakers
delate elated
slaw laws
slat lats
slap laps
insculp sculpin
slab labs
dread readd
outwalk walkout
german manger
peso opes
eras rase
eras sera
lits slit
snick nicks
vena nave
ethos those
low owl
trickles strickle
nana nana
labs slab
khan hank
khan ankh
vee eve
cows scow
slicker lickers
outrun runout
kas ask
stamp tamps
secpar parsec
wings swing
laggings slagging
kats skat
stave vesta
molders smolder
slapper lappers
outer route
shewer hewers
enounced denounce
aglee eagle
tarriers starrier
demo mode
demy emyd
carpings scarping
sager agers
weeps sweep
ear are
eat ate
eat tea
tsetse tsetse
smack macks
ates sate
pans span
sparge parges
setup upset
swearer wearers
side ides
tales stale
taler alert
dol old
alarm malar
cotes escot
takeout outtake
peseta etapes
uns sun
height eighth
upstand standup
abut tabu
asset tasse
lows slow
rouping ingroup
outback backout
sasses assess
cummers scummer
pelts spelt
palls spall
skeet keets
smatter matters
smiter miters
emyd demy
sheather heathers
ousel louse
tagrag ragtag
spectate pectates
estop stope
estop topes
dice iced
dice cedi
pectates spectate
valval valval
wearers swearer
vile evil
slung lungs
roupet troupe
ambler ramble
wipes swipe
lashings slashing
teaks steak
quads squad
lease easel
tuffs stuff
adits tsadi
lings sling
amps samp
legate telega
singly lysing
necks sneck
slaking lakings
eschar chares
screw crews
scummer cummers
duper perdu
gogo gogo
hatters shatter
smog mogs
she hes
mis ism
spelter pelters
trews strew
hoddens shodden
agree eagre
tates testa
tates state
elects select
ads sad
add dad
sordine ordines
oak koa
kail ilka
stray trays
strap traps
plats splat
motes smote
tor ort
top opt
trokes stroke
barde ardeb
barde debar
haddocks shaddock
snow nows
snob nobs
weewee weewee
niggles sniggle
swale wales
niggers snigger
eld del
baba baba
eaved deave
drave raved
hammers shammer
tepas paste
overpass passover
overlay layover
stele teles
alan anal
spotter potters
malts smalt
casebook bookcase
hist this
rowth throw
hunts shunt
ya ay
sambo ambos
nails snail
hods shod
hallows shallow
revile eviler
palpal palpal
aced dace
cutline linecut
nene nene
lubbers slubber
nappers snapper
codling lingcod
sprayer prayers
slower lowers
spree prees
trippers stripper
downturn turndown
lakings slaking
rave aver
rave vera
livers sliver
boxwood woodbox
tables ablest
tables stable
spirea aspire
emanate manatee
yawn awny
remit mitre
unsets sunset
spool pools
flea leaf
haet thae
okeh hoke
okes soke
scone cones
slier liers
stime times
amen name
reft tref
pews spew
sparking parkings
creeds screed
scarer carers
pompom pompom
tasse asset
jihad hadji
swage wages
dikdik dikdik
kayo okay
shale hales
tings sting
swindles windless
old dol
lungs slung
warms swarm
terreen reenter
rochet troche
pye yep
lowings slowing
windless swindles
puns spun
sad ads
say ays
aside ideas
addles saddle
stopping toppings
meal alme
bone ebon
ticklers stickler
esteem mestee
cuttles scuttle
uit tui
estrin trines
slipover overslip
campings scamping
select elects
schiller chillers
rhea hear
spore pores
its sit
licks slick
alls sall
murmur murmur
sidle idles
hots shot
scuff cuffs
manger german
harps sharp
neaps sneap
imbed bedim
seel eels
seel else
picks spick
pineal alpine
shame hames
woodworm wormwood
harks shark
scooper coopers
sown owns
tools stool
tepa pate
argol largo
trappers strapper
keto toke
ramp pram
rami amir
arrest tarres
ullages sullage
umps sump
strumpet trumpets
slowing lowings
pikes spike
oread adore
slaver lavers
hahs shah
spill pills
tinters stinter
swithe withes
sheal heals
shear hears
palpi pipal
rater terra
smite mites
outroll rollout
quirts squirt
tough ought
wishers swisher
sticker tickers
swell wells
kabab babka
outread readout
ephas phase
hovers shover
hops shop
sterna astern
pontoons spontoon
than hant
lumps slump
sledge ledges
sallow allows
ains sain
setoff offset
cares escar
cares scare
tillers stiller
welters swelter
sweeper weepers
pouters spouter
quids squid
squire quires
squirt quirts
trainings straining
tones stone
deke eked
heaves sheave
printings sprinting
milers smiler
offcast castoff
ledges sledge
tacos costa
relate elater
outpull pullout
steelie eeliest
watt twat
seton onset
unroofs sunroof
dunite united
sneck necks
aye yea
leeks sleek
tungs stung
topples stopple
obi bio
snide nides
shist hists
stiff tiffs
plays splay
outers souter
scrimp crimps
ingest tinges
hafts shaft
sperm perms
nibs snib
stump tumps
swigging wiggings
culls scull
shill hills
upset setup
shake hakes
castoff offcast
allover overall
sagger aggers
skill kills
offset setoff
gluten englut
lavers slaver
lights slight
ort tor
coco coco
workout outwork
overhang hangover
prangs sprang
comedown downcome
lingcod codling
said aids
sain ains
sail ails
shaver havers
upgrown grownup
nows snow
spawn pawns
overs verso
spoke pokes
bolo lobo
bolo obol
sculpin insculp
imid midi
sling lings
slink links
shog hogs
sporter porters
hellers sheller
peri ripe
creams scream
omen meno
omen nome
ours sour
sideway wayside
repp prep
gaga gaga
eros rose
stacker tackers
then hent
pas asp
pas spa
pal alp
pam amp
taws staw
plashers splasher
spick picks
troves strove
tripos ripost
shack hacks
karma makar
pines spine
scarper carpers
aba baa
flyblow blowfly
shark harks
share hares
shard hards
rya yar
sold olds
epos pose
crawls scrawl
lookout outlook
ports sport
cads scad
ager rage
nubs snub
oots soot
hoers shoer
ewe wee
ruth thru
shovel hovels
snag nags
bio obi
sword words
server verser
scall calls
serin rinse
skat kats
papa papa
rinse serin
rede dere
sink inks
stinter tinters
walkout outwalk
twat watt
tan ant
lysing singly
drape raped
dad add
toke keto
slacker lackers
griffin riffing
indent dentin
laps slap
udo oud
hists shist
runout outrun
selection elections
wales swale
stopple topples
heals sheal
sewer ewers
stoper topers
sleek leeks
sleet leets
slunk lunks
tamps stamp
muse emus
arval larva
free reef
evil vile
cookout outcook
camps scamp
pope pepo
earth heart
lickers slicker
stippler tipplers
prees spree
turnup upturn
levo vole
leva vale
swindle windles
mome memo
corners scorner
odiums sodium
delude eluded
mirks smirk
scollop collops
nobs snob
ignores signore
addled daddle
lambed bedlam
geste egest
so os
puddings spudding
slick licks
inspect pectins
lowdowns slowdown
vestee steeve
trundle rundlet
calls scall
insole oleins
skidder kidders
allows sallow
trappings strapping
arse sear
arse ears
motmot motmot
stale tales
gale egal
splay plays
splat plats
art tar
arc car
are ear
arm mar
troys stroy
traits strait
prom romp
leaf flea
leap plea
tarres arrest
metre remet
iced cedi
iced dice
slug lugs
ices sice
pryers spryer
tau uta
tap apt
tar art
tae eta
surge urges
sill ills
easel lease
semen mense
kiers skier
centre recent
dope oped
sice ices
idlers sidler
mashers smasher
pintails tailspin

Exercise 11.11 (Liu)


In [3]:
def read_dictionary(filename):
    """Reads from a file and builds a dictionary that maps from
    each word to a string that describes its primary pronunciation.

    Secondary pronunciations are added to the dictionary with
    a number, in parentheses, at the end of the key, so the
    key for the second pronunciation of "abdominal" is "abdominal(2)".

    filename: string
    returns: map from string to pronunciation
    """
    d = dict()
    fin = open(filename)
    for line in fin:

        # skip over the comments
        if line[0] == '#': continue

        t = line.split()
        word = t[0].lower()
        pron = ' '.join(t[1:])
        d[word] = pron

    return d

d_pron = read_dictionary("/Users/lh15/Documents/workspace/c06d.txt")

for word in d_pron:
    ## first, make the 2 variations of the original words, 
    ## and then check their exitance in the word_pronunciation_list.
    ## if they both exist and have the same pronuciation as the original word.
    first_char = word[0]
    word_var_1 = word[1:]
    word_var_2 = first_char + word_var_1[1:]

    if word_var_1 in d_pron and word_var_2 in d_pron and d_pron[word_var_1] == d_pron[word] and d_pron[word_var_2] == d_pron[word]:
        print 'homophone: ' + word


homophone: llana
homophone: eerie
homophone: aaronson
homophone: llama
homophone: ee
homophone: llanes
homophone: llano
homophone: scent
homophone: llamas
homophone: ooohs
homophone: oooh
homophone: lloyd
homophone: aaron
homophone: llewellyn

In [ ]: