Loops that add and count: sequences, sums and combinations
Why this matters
Numbers that follow a rule turn up all through AI work. A learning rate that halves every thousand steps is a sequence. So is the size of a chat that grows with every turn, and adding it up answers a plain question: what does the whole conversation cost? Counting is the other half. Three settings with four values each make 64 experiments, and a model picks each word from tens of thousands, so the number of sentences it could write has no room in any memory. This lesson makes loops that add and loops that count into one habit: write the rule, then check it with a loop.
- Describe a sequence by its rule, and jump to any term without walking there
- Tell a sequence that adds the same amount from one that multiplies by the same amount
- Add a sequence up with a loop, with sum() and with the pairing shortcut, and read a running total
- Count the results of several choices by multiplying, and count orders and groups with math.factorial, math.comb and itertools
- Judge when trying every possibility is out of reach
The idea: a rule makes the next term, and choices multiply
This lesson rests on Sequences and Σ (Foundation lesson 26) and Counting (Foundation lesson 87). It turns both into loops you can run.
A sequence is a list of numbers made by a rule. Each number is a term. The rule has two parts: where it starts, and how each term comes from the one before. Two rules cover most of what you'll meet:
- Arithmetic: add the same step each time. After n steps the term is
start + step * n. - Geometric: multiply by the same ratio each time. After n steps the term is
start * ratio ** n.
A running total adds the terms as you go, and the plain sum is its last number. Step through one sequence and its total: a chat app that sends the whole conversation every turn, with each turn adding 300 tokens.