Skip to content

Commit

Permalink
Add Python3 support
Browse files Browse the repository at this point in the history
Edits:
 - Replace print statement with print function
 - Replace xrange with range
 - Replace iter* in dict methods (e.g. iteritems())
 - Replace generator.next() with next(generator) (available since python 2.6 release in 2008)
 - Explicit id based hash function for Pmf
  • Loading branch information
Recursing committed May 15, 2020
1 parent c681659 commit c1fc219
Show file tree
Hide file tree
Showing 28 changed files with 288 additions and 254 deletions.
21 changes: 11 additions & 10 deletions code/brfss.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

import math
import sys
Expand Down Expand Up @@ -58,7 +59,7 @@ def Recode(self):
"""Recode variables that need cleaning."""

def CleanWeight(weight):
if weight in [7777, 9999]:
if weight in [7777, 9999, 'NA']:
return 'NA'
elif weight < 1000:
return weight / 2.2
Expand Down Expand Up @@ -95,13 +96,13 @@ def SummarizeHeight(self):
[d[r.sex].append(r.htm3) for r in self.records if r.htm3 != 'NA']
[d['all'].append(r.htm3) for r in self.records if r.htm3 != 'NA']

print 'Height (cm):'
print 'key n mean var sigma cv'
for key, t in d.iteritems():
print('Height (cm):')
print('key n mean var sigma cv')
for key, t in d.items():
mu, var = thinkstats.TrimmedMeanVar(t)
sigma = math.sqrt(var)
cv = sigma / mu
print key, len(t), mu, var, sigma, cv
print(key, len(t), mu, var, sigma, cv)

return d

Expand All @@ -113,13 +114,13 @@ def SummarizeWeight(self):
[d[r.sex].append(r.weight2) for r in self.records if r.weight2 != 'NA']
[d['all'].append(r.weight2) for r in self.records if r.weight2 != 'NA']

print 'Weight (kg):'
print 'key n mean var sigma cv'
for key, t in d.iteritems():
print('Weight (kg):')
print('key n mean var sigma cv')
for key, t in d.items():
mu, var = thinkstats.TrimmedMeanVar(t)
sigma = math.sqrt(var)
cv = sigma / mu
print key, len(t), mu, var, sigma, cv
print(key, len(t), mu, var, sigma, cv)


def SummarizeWeightChange(self):
Expand All @@ -130,7 +131,7 @@ def SummarizeWeightChange(self):

changes = [(curr - prev) for curr, prev in data]

print 'Mean change', thinkstats.Mean(changes)
print('Mean change', thinkstats.Mean(changes))


def main(name, data_dir='.'):
Expand Down
6 changes: 4 additions & 2 deletions code/columns.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function


import csv

Expand All @@ -16,7 +18,7 @@ def read_csv(filename, constructor):
fp = open(filename)
reader = csv.reader(fp)

header = reader.next()
header = next(reader)
names = [s.lower() for s in header]

objs = [make_object(t, names, constructor) for t in reader]
Expand Down Expand Up @@ -47,7 +49,7 @@ def print_cols(cols):
cols: list of columns
"""
for i, col in enumerate(cols):
print i, col[0], col[1]
print(i, col[0], col[1])


def make_col_dict(cols, names):
Expand Down
3 changes: 2 additions & 1 deletion code/cookie.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

from thinkbayes import Pmf

Expand All @@ -16,4 +17,4 @@

pmf.Normalize()

print pmf.Prob('Bowl 1')
print(pmf.Prob('Bowl 1'))
3 changes: 2 additions & 1 deletion code/cookie2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

from thinkbayes import Pmf

Expand Down Expand Up @@ -55,7 +56,7 @@ def main():
pmf.Update('vanilla')

for hypo, prob in pmf.Items():
print hypo, prob
print(hypo, prob)


if __name__ == '__main__':
Expand Down
3 changes: 2 additions & 1 deletion code/correlation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

import math
import random
Expand Down Expand Up @@ -171,7 +172,7 @@ def CorrelatedGenerator(rho):
x = random.gauss(0, 1)
yield x

sigma = math.sqrt(1 - rho**2);
sigma = math.sqrt(1 - rho**2)
while True:
x = random.gauss(x * rho, sigma)
yield x
Expand Down
5 changes: 3 additions & 2 deletions code/dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

from thinkbayes import Suite

Expand All @@ -27,13 +28,13 @@ def main():
suite = Dice([4, 6, 8, 12, 20])

suite.Update(6)
print 'After one 6'
print('After one 6')
suite.Print()

for roll in [4, 8, 7, 7, 2]:
suite.Update(roll)

print 'After more rolls'
print('After more rolls')
suite.Print()


Expand Down
3 changes: 2 additions & 1 deletion code/dungeons.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

import random

Expand All @@ -23,7 +24,7 @@ def __init__(self, sides, name=''):
name: string
"""
thinkbayes.Pmf.__init__(self, name=name)
for x in xrange(1, sides+1):
for x in range(1, sides+1):
self.Set(x, 1)
self.Normalize()

Expand Down
17 changes: 9 additions & 8 deletions code/euro.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

"""This file contains a partial solution to a problem from
MacKay, "Information Theory, Inference, and Learning Algorithms."
Expand Down Expand Up @@ -59,7 +60,7 @@ def Likelihood(self, data, hypo):

def UniformPrior():
"""Makes a Suite with a uniform prior."""
suite = Euro(xrange(0, 101))
suite = Euro(range(0, 101))
return suite


Expand Down Expand Up @@ -89,17 +90,17 @@ def RunUpdate(suite, heads=140, tails=110):

def Summarize(suite):
"""Prints summary statistics for the suite."""
print suite.Prob(50)
print(suite.Prob(50))

print 'MLE', suite.MaximumLikelihood()
print('MLE', suite.MaximumLikelihood())

print 'Mean', suite.Mean()
print 'Median', thinkbayes.Percentile(suite, 50)
print('Mean', suite.Mean())
print('Median', thinkbayes.Percentile(suite, 50))

print '5th %ile', thinkbayes.Percentile(suite, 5)
print '95th %ile', thinkbayes.Percentile(suite, 95)
print('5th %ile', thinkbayes.Percentile(suite, 5))
print('95th %ile', thinkbayes.Percentile(suite, 95))

print 'CI', thinkbayes.CredibleInterval(suite, 90)
print('CI', thinkbayes.CredibleInterval(suite, 90))


def PlotSuites(suites, root):
Expand Down
9 changes: 5 additions & 4 deletions code/euro2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

"""This file contains a partial solution to a problem from
MacKay, "Information Theory, Inference, and Learning Algorithms."
Expand Down Expand Up @@ -58,7 +59,7 @@ def Likelihood(self, data, hypo):


def Version1():
suite = Euro(xrange(0, 101))
suite = Euro(range(0, 101))
heads, tails = 140, 110
dataset = 'H' * heads + 'T' * tails

Expand All @@ -69,7 +70,7 @@ def Version1():


def Version2():
suite = Euro(xrange(0, 101))
suite = Euro(range(0, 101))
heads, tails = 140, 110
dataset = 'H' * heads + 'T' * tails

Expand All @@ -78,7 +79,7 @@ def Version2():


def Version3():
suite = Euro2(xrange(0, 101))
suite = Euro2(range(0, 101))
heads, tails = 140, 110

suite.Update((heads, tails))
Expand All @@ -88,7 +89,7 @@ def Version3():
def main():

suite = Version3()
print suite.Mean()
print(suite.Mean())

thinkplot.Pmf(suite)
thinkplot.Show()
Expand Down
21 changes: 11 additions & 10 deletions code/euro3.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function

"""This file contains a partial solution to a problem from
MacKay, "Information Theory, Inference, and Learning Algorithms."
Expand Down Expand Up @@ -72,32 +73,32 @@ def Main():

suite = Euro()
like_f = suite.Likelihood(data, 50)
print 'p(D|F)', like_f
print('p(D|F)', like_f)

actual_percent = 100.0 * 140 / 250
likelihood = suite.Likelihood(data, actual_percent)
print 'p(D|B_cheat)', likelihood
print 'p(D|B_cheat) / p(D|F)', likelihood / like_f
print('p(D|B_cheat)', likelihood)
print('p(D|B_cheat) / p(D|F)', likelihood / like_f)

like40 = suite.Likelihood(data, 40)
like60 = suite.Likelihood(data, 60)
likelihood = 0.5 * like40 + 0.5 * like60
print 'p(D|B_two)', likelihood
print 'p(D|B_two) / p(D|F)', likelihood / like_f
print('p(D|B_two)', likelihood)
print('p(D|B_two) / p(D|F)', likelihood / like_f)

b_uniform = Euro(xrange(0, 101))
b_uniform = Euro(range(0, 101))
b_uniform.Remove(50)
b_uniform.Normalize()
likelihood = SuiteLikelihood(b_uniform, data)
print 'p(D|B_uniform)', likelihood
print 'p(D|B_uniform) / p(D|F)', likelihood / like_f
print('p(D|B_uniform)', likelihood)
print('p(D|B_uniform) / p(D|F)', likelihood / like_f)

b_tri = TrianglePrior()
b_tri.Remove(50)
b_tri.Normalize()
likelihood = b_tri.Update(data)
print 'p(D|B_tri)', likelihood
print 'p(D|B_tri) / p(D|F)', likelihood / like_f
print('p(D|B_tri)', likelihood)
print('p(D|B_tri) / p(D|F)', likelihood / like_f)


if __name__ == '__main__':
Expand Down
Loading

0 comments on commit c1fc219

Please sign in to comment.