Skip to content

Instantly share code, notes, and snippets.

@gulan
Created December 7, 2016 01:45
Show Gist options
  • Select an option

  • Save gulan/4d6bc074d936c9427b9ca4b2087e406b to your computer and use it in GitHub Desktop.

Select an option

Save gulan/4d6bc074d936c9427b9ca4b2087e406b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
data = """a 9
b 2
c 2
d 4
e 12
f 2
g 3
h 2
i 9
j 1
k 1
l 1
m 2
n 6
o 8
p 2
q 1
r 6
s 4
t 6
u 4
v 2
w 2
x 1
y 2
z 1
""" # final blank line needed to denote EOF
"""
data = line* . eof
line = letter . space . count . newline
count = digit+
eof = newline
"""
class string_reader(object):
def __init__(self, st):
self.ix, self.st = 0, st
def getch(self):
self.ix += 1
return self.st[self.ix-1]
def is_letter(ch): return 'a' <= ch <= 'z'
def is_digit(ch): return '0' <= ch <= '9'
def load_pairs(data=data):
# do it the hard way
sr = string_reader(data)
counts = []
ch = sr.getch()
while ch != '\n':
assert is_letter(ch), `ch`
letter = ch
ch = sr.getch()
assert ch == ' ', `ch`
count = 0
ch = sr.getch()
while is_digit(ch):
count = 10 * count + (ord(ch) - ord('0'))
ch = sr.getch()
assert ch == '\n', `ch`
counts.append((letter, count))
ch = sr.getch()
return counts
def load_pairs_adhoc(data=data): # not used
return [
(ch,int(n)) for (ch,n) in [
s.strip().split() for s in data.strip().split('\n')]]
def prob_distribution(counts):
total = 1.0 * sum(i for (_,i) in counts)
return set((ch,i/total) for (ch,i) in counts)
"""
A set of disjoint outcomes is an 'event'. The probability of an event
is the sum of probabilities of its outcomes.
Compute the probability of drawing a vowel from the intital set of
scrabble tiles.
"""
pb = prob_distribution(load_pairs())
VOWELS = set(ch for ch in "aeiou")
print sum(p for (l,p) in pb if l in VOWELS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment