Python Foundations & The 6-Step Method · Lesson 4 of 5

The 6-Step Method — A Worked Example

This is a repeatable way to attack any problem without freezing up. Watch all six steps play out on one classic — once you've seen it, you can copy the shape every time.

By Shahriyar · Updated

The idea, in one line

Don't rush to code. Understand the problem, try a slow-but-simple idea, make it faster, then write it — in that order.

1 · Restate

Say it back in your own words: given text, return the first character (reading left to right) whose count in the whole string is exactly one. In: a string. Out: one character, or a signal if there is none.

2 · Examples

Write a few by hand, including a tricky one:

3 · Brute force

Reach for the obvious slow idea first: for each character, scan the whole string and count how many times it appears; return the first one whose count is 1. It works — even though it re-scans a lot.

4 · Optimize

All that re-scanning is wasted effort. Instead, count every character once into a dict, then make a second left-to-right pass and return the first character whose stored count is 1. Two passes instead of many.

5 · Code

▸ first_unique.py
def first_unique(text):
    # Step 4: count each character once
    counts = {}
    for ch in text:
        counts[ch] = counts.get(ch, 0) + 1

    # Second pass, left to right: first with count 1 wins
    for ch in text:
        if counts[ch] == 1:
            return ch
    return None            # edge case: nothing was unique

print(first_unique("swiss"))   # w
print(first_unique("aabb"))    # None
print(first_unique("z"))       # z

6 · Trace

Check it by hand. For "swiss" the counts are s→3, w→1, i→1. Second pass: s (3) skip, w (1) → return "w". It matches the example you wrote in step 2 — that match is your proof.

The house method — restate, examples, brute force, optimize, code, trace

All lessons in Python Foundations & The 6-Step Method

  1. Variables, Types, Control Flow & Functions
  2. Lists, Dicts, Sets & Tuples — When and Why
  3. String Manipulation Patterns
  4. The 6-Step Method — A Worked Example
  5. Hand-Tracing — Where Logic Actually Grows