The Odd Digits

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
Asked in
Athenahealth

Problem

You are handed a string of mixed characters, like a scraped token where the useful signal is buried among letters and separators. Pull out only the characters that are digits with an odd value, keeping them in the order they appear, and return them joined as a string.

Hidden inside a mess of characters are a few odd numbers.

Example 1

Input:

s = "a1b2c3d4e5"

Output:

"135"

Example 2

Input:

s = "hello123"

Output:

"13"

Worked solution and explanation

The real problem under the costume

Underneath the word-problem this is a guarded per-character filter. The skill being probed: walk the string once and keep a character only when it is a digit AND its value is odd. Anyone can write the loop. The two things that actually separate candidates are ordering the checks so int() never sees a letter, and remembering that '0' is even so it falls out with 2, 4, 6 and 8. Flip the condition order and one stray letter throws a ValueError; forget zero and every '0' leaks into your answer.


Break down the requirements

Step 1: Iterate through each character

Scan the string one character at a time, so a minus sign or a run of digits like '203' is read as separate characters, never as a whole number.

Step 2: Guard the conversion, then check oddness

Confirm the character is numeric with ch.isdigit() FIRST, then test oddness with int(ch) % 2 != 0. The order is load-bearing: the digit check short-circuits before int() ever touches a letter.

Step 3: Build the result string

Collect the survivors and join them into a string. No matches (or empty input) naturally yields an empty string, which is exactly the contract.


The solution

Single-pass digit extraction with a guarded oddness check
def extract_odd_from_string(s: str) -> str:
    result = []
    for ch in s:
        if ch.isdigit() and int(ch) % 2 != 0:
            result.append(ch)
    return ''.join(result)

Common follow-up questions