Algorithmscharacter comparison

Character Comparison

TT
Testlaa Team
May 14, 20261 min read

Single-character comparison reduces to code-point order or locale-aware collation for strings. For ASCII contests, ==, <, > on one-length strings match ord comparisons.

Why this shows up in the real world

Admission ticket codes compare character-by-character at the gate. Genetic bases A,C,G,T use custom ordering for complements—not ASCII alphabetical.

Core idea (explained for students)

Guard length: only compare if both strings length 1 (or compare s[i] slices). Use key=ord when sorting single letters for ASCII contests.

Try this in Python

def next_capital_letter(ch: str) -> str | None:
    if len(ch) != 1 or not ("A" <= ch <= "Z"):
        return None
    if ch == "Z":
        return None
    return chr(ord(ch) + 1)


print(next_capital_letter("M"))

Common mistakes

  • Comparing a character to a length>1 string accidentally.
  • Assuming == ignores case—use lower() both sides first.

Key takeaways

  • For multi-character strings, comparisons are lexicographic, not numeric.
  • Centralize cmp_char(a,b) helpers in parsing code.

Tags:

StringsPythonStudents