Python Challenge - Level 3

Problem

One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.

The page source contains a large block of mixed-case letters. Find every lowercase letter that is flanked by exactly three uppercase letters on each side — no more, no less.

Pattern: UUUlUUU where U = uppercase, l = lowercase.

Solution

The key constraint is exactly 3: [A-Z]{3} must not be preceded or followed by another uppercase letter.

Python

import urllib.request, re

html = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/equality.html").read().decode()
data = re.findall(r"<!--(.*)-->", html, re.DOTALL)[-1]

# [^A-Z] ensures no 4th uppercase letter bleeds in from either side
matches = re.findall(r"(?<=[^A-Z])[A-Z]{3}([a-z])[A-Z]{3}(?=[^A-Z])", data)
print("".join(matches))  # linkedlist

Why (?<=[^A-Z]) instead of [^A-Z]+ in the pattern? Using a lookbehind/lookahead avoids consuming the guard characters, which prevents overlapping matches from being missed.

Go

Go's regexp package supports lookarounds only via the re2 syntax — which does not support lookbehind. Work around it by capturing the guard characters explicitly:

package main

import (
    "fmt"
    "io"
    "net/http"
    "regexp"
    "strings"
)

func main() {
    resp, _ := http.Get("http://www.pythonchallenge.com/pc/def/equality.html")
    body, _ := io.ReadAll(resp.Body)

    // Extract last HTML comment
    commentRe := regexp.MustCompile(`(?s)<!--(.*)-->`)
    data := string(commentRe.FindSubmatch(body)[1])

    // Capture guard + target + guard; index 1 is the lowercase letter
    re := regexp.MustCompile(`[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]`)
    var result strings.Builder
    // Step by 1 to avoid skipping overlapping matches
    for i := 0; i < len(data)-8; i++ {
        if m := re.FindStringSubmatch(data[i : i+8]); m != nil {
            result.WriteString(m[1])
        }
    }
    fmt.Println(result.String()) // linkedlist
}

Rust

Rust's regex crate also uses RE2 (no lookbehind). Same workaround — sliding window of fixed size:

use regex::Regex;

fn main() {
    let data = "..."; // extracted HTML comment content
    let re = Regex::new(r"[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]").unwrap();

    let answer: String = (0..data.len().saturating_sub(8))
        .filter_map(|i| {
            re.captures(&data[i..std::cmp::min(i + 8, data.len())])
                .and_then(|caps| caps.get(1))
                .map(|m| m.as_str().chars().next().unwrap())
        })
        .collect();

    println!("{}", answer); // linkedlist
}

Language Comparison

Feature Python Go Rust
Regex engine PCRE-compatible — supports lookbehind (?<=[^A-Z]) RE2 — no lookbehind; must use consuming patterns RE2 (via regex crate) — no lookbehind
Overlapping matches Need re.findall with lookarounds OR step manually Must slide a fixed window manually Must slide a fixed window manually
Named captures (?P<name>...) (?P<name>...) (?P<name>...)
Multiline / DOTALL re.DOTALL flag (?s) inline (?s) inline

Key insight: This puzzle exposes the most important practical difference between Python's re and Go/Rust's RE2 engines — lookbehind assertions. Python's (?<=[^A-Z]) elegantly solves the "exactly 3" boundary problem without consuming characters. Go and Rust require a sliding-window workaround because their engines guarantee linear-time matching by banning lookbehind.

Next Level

http://www.pythonchallenge.com/pc/def/linkedlist.php