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