fork download
  1. from random import choice
  2.  
  3. def build_suffixes(txt, k):
  4. suffixes = {}
  5. prefix = tuple([None] * k)
  6.  
  7. for word in txt:
  8. if prefix in suffixes:
  9. suffixes[prefix] += [word]
  10. else:
  11. suffixes[prefix] = [word]
  12. prefix = prefix[1:k] + tuple([word])
  13.  
  14. suffixes[prefix] = [None]
  15. return suffixes
  16.  
  17. def generate_text(suffixes, k):
  18. prefix = tuple([None] * k)
  19. suffix = suffixes[prefix][0]
  20.  
  21. txt = []
  22. while suffix != None:
  23. txt.append(suffix)
  24. prefix = prefix[1:k] + tuple([suffix])
  25. suffix = choice(suffixes[prefix])
  26.  
  27. return ' '.join(txt)
  28.  
  29. txt = """Blessed are the poor in spirit,
  30. for theirs is the kingdom of heaven.
  31. Blessed are those who mourn,
  32. for they will be comforted.
  33. Blessed are the meek,
  34. for they will inherit the earth.
  35. Blessed are those who hunger and thirst for righteousness,
  36. for they will be filled.
  37. Blessed are the merciful,
  38. for they will be shown mercy.
  39. Blessed are the pure in heart,
  40. for they will see God.
  41. Blessed are the peacemakers,
  42. for they will be called sons of God."""
  43.  
  44. k = 2
  45. s = build_suffixes(txt.split(), k)
  46. t = generate_text(s, k)
  47. print(t)
Success #stdin #stdout 0.02s 11448KB
stdin
Standard input is empty
stdout
Blessed are the merciful, for they will inherit the earth. Blessed are the peacemakers, for they will inherit the earth. Blessed are the pure in heart, for they will inherit the earth. Blessed are the peacemakers, for they will be called sons of God.