Python Challenge - Level 2

Problem

recognize the characters. maybe they are in the book, but MAYBE they are in the page source.

The page source contains a huge HTML comment block packed with noise characters ($@#!^ etc.) — the actual message is hidden as the rare letters that appear only once.

Solution

Python

collections.Counter is the natural fit — count all characters, filter to those appearing exactly once:

import urllib.request, re, collections

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

freq = collections.Counter(data)
answer = "".join(c for c in data if freq[c] == 1 and c.isalpha())
print(answer)  # equality

Go

Go uses a map[rune]int for frequency counting:

package main

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

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

    re := regexp.MustCompile(`(?s)<!--(.*?)-->`)
    matches := re.FindAllSubmatch(body, -1)
    data := string(matches[len(matches)-1][1])

    freq := make(map[rune]int)
    for _, c := range data {
        freq[c]++
    }

    var answer []rune
    for _, c := range data {
        if freq[c] == 1 && unicode.IsLetter(c) {
            answer = append(answer, c)
        }
    }
    fmt.Println(string(answer)) // equality
}

Rust

Rust uses HashMap and a two-pass approach:

use std::collections::HashMap;

fn find_rare(data: &str) -> String {
    let mut freq: HashMap<char, usize> = HashMap::new();
    for c in data.chars() {
        *freq.entry(c).or_insert(0) += 1;
    }
    data.chars()
        .filter(|c| c.is_alphabetic() && freq[c] == 1)
        .collect()
}

fn main() {
    // In practice: fetch HTML, extract last HTML comment block
    let data = "%%$@_$^__#)eq^u)&!al_+]!*i@&^t}@[@y%]"; // simplified
    println!("{}", find_rare(data)); // equality
}

Language Comparison

Feature Python Go Rust
Frequency counting collections.Counter — one call map[rune]int — manual loop HashMap<char, usize> — manual loop
Filter rare chars Generator expression Second loop over runes .filter() on iterator chain
Regex with DOTALL re.DOTALL flag (?s) inline flag (?s) via regex crate
HTML fetching urllib.request stdlib net/http stdlib reqwest crate (external)

Key insight: Python's Counter makes frequency analysis a one-liner. In Go and Rust, the same logic requires explicit map operations — but the algorithmic clarity is identical. The real difference is in the HTTP + regex ecosystem: Python's stdlib covers both, Rust typically reaches for external crates.

Next Level

http://www.pythonchallenge.com/pc/def/equality.html