The Alphabet Score
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a string, return the sum of alphabetic character values where a=1..z=26, case-insensitive. Non-alphabetic characters contribute 0.
Every letter has a secret numeric value - what's your total?
Example 1
Input:
s = "abc"
Output:
6
Example 2
Input:
s = "z"
Output:
26
Worked solution and explanation
Why this problem exists in real interviews
Character-to-value scoring tests whether you know the ord/chr ASCII trick or whether you'd build a 26-entry dict by hand. Interviewers grade this on how cleanly you state the alphabetic-only filter, how you handle case, and whether your final expression is a single sum() over a generator (Pythonic) or a manual accumulator (junior).
Break down the requirements
Step 1: Lowercase once, filter alphabetic
Lowercase the entire string up front so you only need one ord-anchor (ord('a')). Use str.isalpha() to skip non-letters; this also correctly handles digits, punctuation, and whitespace as zero contributions.
Step 2: Convert each letter with ord arithmetic
For a lowercase letter c, the value is ord(c) - ord('a') + 1. This maps 'a' to 1 and 'z' to 26 in one expression with no lookup table. Memorizing this idiom saves you from constructing a 26-item dict, which is the most common over-engineering.
Step 3: Sum in one expression
Wrap the conversion in a generator expression inside sum(). It runs in C, allocates no intermediate list, and reads as the spec sentence: 'sum of alphabetic character values.' Empty input returns 0 with no special case.
The solution
def convert_string_mapping(s: str) -> int:
s = s.lower()
return sum(ord(c) - ord('a') + 1 for c in s if c.isalpha())Common follow-up questions
- How would the solution change for case-sensitive scoring (uppercase contributes 27..52)? (branch on isupper() or build a small dict; show both.)
- What if the alphabet weights are arbitrary (e.g., Scrabble values)? (replace ord-arithmetic with a dict lookup; mention str.translate for very hot paths.)
- How would you score a 10 GB text file without loading it all? (stream chunk by chunk, accumulate the sum; note that lowercasing on chunk boundaries is safe for ASCII but not for some Unicode case-folding edge cases.)