Skip to content

Instantly share code, notes, and snippets.

@MollsReis
Last active December 14, 2015 18:52
Show Gist options
  • Select an option

  • Save MollsReis/e102638841a6d5d8b757 to your computer and use it in GitHub Desktop.

Select an option

Save MollsReis/e102638841a6d5d8b757 to your computer and use it in GitHub Desktop.
Word generation using markov chains
from sys import argv
from collections import defaultdict
from random import choice
class DefaultList(list):
def __getitem__(self, idx):
try:
return super().__getitem__(idx)
except IndexError:
return [None, 3, 1, ""][idx]
argv, dictionary = DefaultList(argv[:]), defaultdict(list)
prefix, count, start = int(argv[1]), int(argv[2]), str(argv[3])
for word in ("^%s$" % line.strip().lower() for line in open("/usr/share/dict/words")):
while len(word) >= prefix + 1:
dictionary[word[:prefix]].append(word[prefix])
word = word[1:]
starters = list(k for k in dictionary.keys() if k[0:len(start) + 1] == "^%s" % start)
for word in [""] * count:
while word == "" or word[-1] != "$":
word += choice(starters if word == "" else dictionary[word[-prefix:]])
print(word[:-1][1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment