Fix the session token entropy estimate
Your task
An assistant wrote a session token generator and called it "cryptographically secure". Before you trust that, your team measures the token space: how many bits of entropy a token can carry. Entropy in bits is how many yes or no guesses it takes to cover every possible token.
An assistant wrote token_entropy_bits(alphabet, length). It is in the editor. It has a bug. Find it and fix it.
Input and output:
alphabet: the characters the generator picks from, as one string.length: how many characters a token has.- Return the entropy in bits as a float. Answers within 0.000001 of the expected value pass.
Rules the tests check:
- Count the distinct characters in
alphabet. A character that appears more than once counts once, and case matters:aandAare two characters. - If
lengthis 0 or less, or there are fewer than 2 distinct characters, return 0. - Otherwise return
lengthtimes the base 2 logarithm of the number of distinct characters.
Examples:
token_entropy_bits("abcdefghijklmnopqrstuvwxyz", 16)returns75.20703549025747: 16 lowercase letters give about 75 bits, not the 128 that "secure" suggests.token_entropy_bits("0123456789abcdef", 32)returns128.token_entropy_bits("abcabc", 10)returns15.849625007211563: there are 3 distinct characters, not 6.
Then, in a sentence or two: how would you catch this kind of bug in review?
Examples
token_entropy_bits(alphabet: str, length: int) -> floatExample 1
Input
token_entropy_bits("abcdefghijklmnopqrstuvwxyz", 16)Output
75.20703549025747Example 2
Input
token_entropy_bits("0123456789abcdef", 32)Output
128Example 3
Input
token_entropy_bits("abcabc", 10)Output
15.849625007211563