Last active
September 24, 2019 19:50
-
-
Save mattharrison/b8a3b0f6b0bda4bb2fc0fe06ecbae6ce to your computer and use it in GitHub Desktop.
markov chain starter code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This is a module docstring. It must be at the TOP | |
of the file. | |
This is the markov module. You can create | |
a markov chain like this: | |
>>> m = Markov('ab') | |
>>> m.predict('a') | |
'b' | |
""" | |
import random | |
class Markov: | |
def __init__(self, text): | |
'This is the constructor docstring' | |
# this is the constructor | |
self.table = get_table(text) | |
def predict(self, data): | |
options = self.table.get(data, {}) | |
if not options: | |
raise KeyError(f'{data} not in training') | |
possibles = [] | |
for key in options: | |
counts = options[key] | |
for i in range(counts): | |
possibles.append(key) | |
return random.choice(possibles) | |
def get_table(text): | |
'''This is a function for creating | |
transition tables: | |
>>> get_table('abac') | |
{'a': {'b': 1}} | |
''' | |
#import pdb; pdb.set_trace() | |
results = {} # empty dictionary literal | |
for i in range(len(text)): | |
char = text[i] | |
try: | |
out = text[i+1] | |
except IndexError: | |
break | |
char_dict = results.get(char, {}) | |
#print(i, char, out, results, char_dict) | |
char_dict.setdefault(out, 0) | |
char_dict[out] = char_dict[out] + 1 | |
results[char] = char_dict | |
return results | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment