Python Challenge - Level 10

Problem

len(a[30]) = ?

Clicking the bull reveals:

a = [1, 11, 21, 1211, 111221,

This is the famous Look-and-Say sequence (Conway sequence):

  • 1 is read as "one 1" → 11
  • 11 is read as "two 1s" → 21
  • 21 is read as "one 2, one 1" → 1211
  • 1211 is read as "one 1, one 2, two 1s" → 111221

We need to find the length of the 30th element (a[0] = 1, a[1] = 11, ...).

Solution

Python

Python provides multiple elegant ways to solve this. The cleanest is itertools.groupby:

import itertools

def next_look_and_say(s: str) -> str:
    return "".join(f"{len(list(group))}{char}" for char, group in itertools.groupby(s))

a = "1"
for _ in range(30):
    a = next_look_and_say(a)

print(len(a))  # 5808

Alternatively, with regular expressions:

import re

a = "1"
for _ in range(30):
    a = re.sub(r"(.)\1*", lambda m: f"{len(m.group(0))}{m.group(1)}", a)

print(len(a))

Go

In Go, we iterate through the bytes using two pointers with strings.Builder for zero unnecessary allocations:

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func nextLookAndSay(s string) string {
	var sb strings.Builder
	n := len(s)
	for i := 0; i < n; {
		j := i
		for j < n && s[j] == s[i] {
			j++
		}
		sb.WriteString(strconv.Itoa(j - i))
		sb.WriteByte(s[i])
		i = j
	}
	return sb.String()
}

func main() {
	s := "1"
	for i := 0; i < 30; i++ {
		s = nextLookAndSay(s)
	}
	fmt.Printf("len(a[30]) = %d\n", len(s)) // 5808
}

Rust

In Rust, we can implement the two-pointer approach using byte slices and a pre-allocated String:

fn next_look_and_say(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut result = String::with_capacity(bytes.len() * 2);
    let mut i = 0;

    while i < bytes.len() {
        let mut j = i;
        while j < bytes.len() && bytes[j] == bytes[i] {
            j += 1;
        }
        result.push_str(&(j - i).to_string());
        result.push(bytes[i] as char);
        i = j;
    }
    result
}

fn main() {
    let mut s = String::from("1");
    for _ in 0..30 {
        s = next_look_and_say(&s);
    }
    println!("len(a[30]) = {}", s.len()); // 5808
}

Language Comparison

Feature Python Go Rust
Consecutive Run Grouping itertools.groupby() built into stdlib Manual two-pointer loop over slices Manual two-pointer loop or external itertools::Itertools::group_by
String Concatenation Performance str.join() builds string in a single memory allocation strings.Builder provides dynamic buffer with minimal reallocations String::with_capacity() allows exact or estimated reservation
Memory Overhead Each run in itertools.groupby produces temporary tuples and lists In-place slice inspection, zero heap allocations during scanning Zero heap allocations during scanning; contiguous byte access
Regex Alternative re.sub(r"(.)\1*", ...) with backreferences regexp package does not support backreferences (\1) regex crate does not support backreferences by default

Key insight: Python's itertools.groupby makes run-length encoding an expressive one-liner. Go and Rust don't have run-length grouping in their standard libraries, but the two-pointer loop operating on byte slices is both straightforward and drastically faster (running 30 iterations in sub-millisecond time). Note also that Go's standard regexp and Rust's regex crate use linear-time finite automata algorithms that deliberately forbid backreferences (\1), making the regex approach uniquely available to Python (which uses a backtracking NFA engine).

Next Level

Replace bull with 5808 in the URL:

http://www.pythonchallenge.com/pc/return/5808.html