liveBook · Manning

Fibonacci sequence

As explained in Regular Expression Puzzles and AI Coding Assistants

The Fibonacci sequence is the numeric sequence in which each term is the sum of the two preceding terms, conventionally beginning with 1 and 1.

What looks like a harmless number puzzle becomes a test of expressive power: each term is the sum of the two before it, beginning 1, 1. The challenge is to recognize Fibonacci-like sequences when numbers are encoded as runs of @ symbols. section 5.13

1 1 2 3 5 8 13 21 34 55 89 144

The opening terms make the recursive pattern visible before the sequence is translated into a string-matching problem. section 5.13

A regular expression must distinguish valid encodings such as “@ @ @@ @@@ @@@@@” from near misses, while also handling Fibonacci-like sequences that begin with other two values. That generalization connects Fibonacci numbers to Lucas sequences, whose initial values are 2 and 1. section 5.13

fibs1 = "@ @ @@ @@@ @@@@@ @@@@@@@@ "                   #1
fibs2 = "@ @ @@ @@@ @@@@@ "                            #2
lucas1 = "@@ @ @@@ @@@@ @@@@@@@ @@@@@@@@@@@ "          #3
lucas2 = "@@@ @ @@@@ @@@@@ @@@@@@@@@ @@@@@@@@@@@@@@ "  #4
wrong1 = "@ @ @@@ @@@@ @@@@@@@ @@@@@@@@@@@ "           #5
wrong2 = "@ @ @@ @@@ @@@@ @@@@@@@ "                    #6
wrong3 = "@ @ @@ @@@@ @@@@@@ "                         #7

The candidate strings provide positive, generalized, and deliberately wrong cases for testing whether a matcher tracks the recursive relationship rather than superficial repetition. section 5.13

An AI-generated answer may look impressively technical without establishing correctness. Its proposed pattern uses anchors, noncapturing groups, and lookaheads, so the useful next move is to test it against valid Fibonacci prefixes, Lucas variants, and wrong strings instead of trusting its explanation. section 5.15 section 5.13

How Regular Expression Puzzles and AI Coding Assistants covers it

How deep it goes
Defines the recursive rule and encoded test problem, then stops short of presenting a verified regular-expression solution.
Examples
Uses 1, 1, 2, 3, 5, 8 and @-encoded Fibonacci, Lucas, and incorrect strings as test cases.
What you can do after
Evaluate regular expressions by testing their apparent logic against valid prefixes, generalizations, and counterexamples.
How it connects
Connects Fibonacci numbers with recursive sequences, Lucas sequences, regular expressions, lookahead assertions, and AI-generated code.

Also explained in

Compare how 6 books explain Fibonacci sequence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Regular Expression Puzzles and AI Coding Assistants. The section links point to the parts of the book it draws on.