Fix the session token entropy estimate

Review the AI's codeEasy10 min

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: a and A are two characters.
  • If length is 0 or less, or there are fewer than 2 distinct characters, return 0.
  • Otherwise return length times the base 2 logarithm of the number of distinct characters.

Examples:

  • token_entropy_bits("abcdefghijklmnopqrstuvwxyz", 16) returns 75.20703549025747: 16 lowercase letters give about 75 bits, not the 128 that "secure" suggests.
  • token_entropy_bits("0123456789abcdef", 32) returns 128.
  • token_entropy_bits("abcabc", 10) returns 15.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) -> float
Example 1
Inputtoken_entropy_bits("abcdefghijklmnopqrstuvwxyz", 16)
Output75.20703549025747
Example 2
Inputtoken_entropy_bits("0123456789abcdef", 32)
Output128
Example 3
Inputtoken_entropy_bits("abcabc", 10)
Output15.849625007211563