Generate letters from a learned model

Train the letter model, then generate: turn each random number into a letter.

What to build

A program that learns letter probabilities from a text and generates one letter per random number.

Requirements

  • Probabilities: each letter's count divided by the number of letters, spaces ignored.
  • For each draw r, walk the letters in alphabetical order adding their probabilities, and choose the first whose running total is greater than r.
  • Print the generated letters as one word.

Input

Line 1: the training text (lower-case letters and spaces). Line 2: the draws, numbers from 0 up to (not including) 1.

Output

One line.

Constraints

1 to 10,000 characters; 1 to 1000 draws.

Example

Input:

banana bandana cabana
0.05 0.62 0.31 0.97 0.48 0.80

Output:

abanbn

Why it works

Each letter owns a slice of the range from 0 to 1 as wide as its probability, so a random number lands in a letter's slice exactly as often as that letter should appear.

Examples

Example 1 · Input
banana bandana cabana
0.05 0.62 0.31 0.97 0.48 0.80
Expected output
abanbn
Example 2 · Input
ab
0.4 0.6
Expected output
ab

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Learn the letter probabilities first (spaces ignored), and keep the letters in alphabetical order.

Hint 2

For each draw r, add up the probabilities in that order and pick the first letter whose running total is greater than r.

Solution

Show one correct solution (try it yourself first)
text = input().replace(" ", "")
draws = list(map(float, input().split()))
counts = {}
for ch in text:
    counts[ch] = counts.get(ch, 0) + 1
letters = sorted(counts)
out = []
for r in draws:
    running = 0.0
    choice = letters[-1]
    for ch in letters:
        running += counts[ch] / len(text)
        if r < running:
            choice = ch
            break
    out.append(choice)
print("".join(out))

Lesson: What generative AI is →