The first step of the simplest text generator: learn how likely each letter is.
What to build
A program that learns the probability of each letter in a text.
Requirements
- Ignore spaces; count every other character.
- Print each different character in alphabetical order with its probability:
C P, with P to 3 decimal places.
Input
One line of lower-case text.
Output
One line per different character.
Constraints
1 to 10,000 characters, with at least one that is not a space.
Example
Input:
banana
Output:
a 0.500
b 0.167
n 0.333
Why it works
Dividing counts by the total turns them into probabilities that add up to 1, which is exactly what a sampler needs.
Examples
Example 1 · Input
banana
Expected output
a 0.500 b 0.167 n 0.333
Example 2 · Input
aab
Expected output
a 0.667 b 0.333
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Skip the spaces, and count every other character.
Hint 2
Each probability is a letter's count divided by the number of letters counted.
Solution
Show one correct solution (try it yourself first)
text = input().replace(" ", "")
counts = {}
for ch in text:
counts[ch] = counts.get(ch, 0) + 1
for ch in sorted(counts):
print(ch, f"{counts[ch] / len(text):.3f}")