Skip to content

Character Utilities

01 · Question

Implement two small character helpers:

  1. is_alphanumeric(c): return whether c is an English letter or digit.
  2. to_uppercase(c): convert a lowercase English letter to uppercase; otherwise return c unchanged.

02 · Analysis

ASCII letters and digits occupy contiguous ranges, so both helpers use direct range checks:

  • Alphanumeric means a-z, A-Z, or 0-9.
  • Uppercase conversion keeps the character's offset from 'a' and applies it from 'A'.

The point: reason with character ranges and relative offsets instead of memorizing numeric ASCII codes.

Complexity: both helpers run in O(1)O(1) time and use O(1)O(1) space.

03 · Solution

Two focused implementations

1. Check whether a character is alphanumeric

1def is_alphanumeric(c: str) -> bool:
2 return ('a' <= c <= 'z') or \
3 ('A' <= c <= 'Z') or \
4 ('0' <= c <= '9')

2. Convert a lowercase character to uppercase

1def to_uppercase(c: str) -> str:
2 if not ('a' <= c <= 'z'):
3 return c
4 return chr(ord(c) - ord('a') + ord('A'))