Created
October 22, 2011 20:42
-
-
Save edma2/1306471 to your computer and use it in GitHub Desktop.
This file contains 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
import sys | |
from random import choice | |
MAXWORDS = 10000 # Max words to output | |
NPREF = 2 # Number of prefix words | |
NONWORD = '\n' # Sentinel word | |
table = {} # {(p1,p2) : [s1, s2, s3]} | |
prefix = tuple([NONWORD for i in range(NPREF)]) | |
wordlist = sys.stdin.read().split() | |
# shiftTuple((1,2,3), 4) => (2,3,4) | |
def shiftTuple(tup, elm): | |
return tuple(list(tup)[1:] + [elm]) | |
################################################## | |
# Build prefix table | |
for word in wordlist: | |
if prefix not in table: table[prefix] = [] | |
table[prefix].append(word) | |
prefix = shiftTuple(prefix, word) | |
table[prefix].append(NONWORD) | |
# Generate output | |
prefix = tuple([NONWORD for i in range(NPREF)]) | |
for i in range(MAXWORDS): | |
if prefix in table: | |
word = choice(table[prefix]) | |
if word == NONWORD: break | |
print word | |
prefix = shiftTuple(prefix, word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment