Index Ai Academy
Phase 0 · Numbers for code

Loops that add and count: sequences, sums and combinations

Sequences that add or multiply each step, a formula for any term, and adding a sequence up.

About 34 minutes · Free lesson

What it covers7

Why it 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.

What you'll be able to do

  • 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
Quick check
A guess before you start. Two savings plans begin with $1. Plan A adds $10 every week. Plan B doubles every week. Which holds more after 10 weeks?
  1. Plan A, by a long way: adding 10 beats doubling 1
  2. They hold about the same after 10 weeks
  3. Plan A until week 20, when plan B catches it
  4. Plan B, by a long way: about ten times as much
Show the answer

Plan B, by a long way: about ten times as much

Plan A reaches 1 + 10 * 10 = $101. Plan B doubles ten times and reaches $1,024. Adding the same amount climbs a straight ramp; multiplying by the same amount curves upward and leaves it behind.

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.

Quick check
From the Foundation: what is 1 + 2 + 3 + ... + 10?
  1. 55
  2. 100
  3. 45
  4. 110
Show the answer

55

Pair the first with the last: 1 + 10 = 11, 2 + 9 = 11, and so on, for 5 pairs: 5 * 11 = 55. The formula is n * (n + 1) / 2.

Try it now

Then change the terms and press Use these numbers: a sum is always a running total.

Counting. Choices made one after another multiply. A training sweep tries 4 learning rates, 3 batch sizes and 5 depths: every learning rate goes with every batch size and every depth, so the sweep has 4 * 3 * 5 = 60 runs. Press Step to fill the slots one at a time.

Two more counts you will need. Orders: 5 books can stand in 5 * 4 * 3 * 2 * 1 = 120 orders, since each place uses one up. That shrinking product is the factorial, 5!. Groups: when only the members matter, count the ordered picks and divide out the orders. A pizza with 2 of 4 toppings: 4 * 3 = 12 ordered picks, each pair counted twice, so 6 pizzas.

In your own words
In your own words: how can you tell whether a sequence is arithmetic or geometric from its terms?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: loops that add and loops that count

A range(start, stop, step) is an arithmetic sequence, and it stops before stop. Jump to a term with the formula instead of walking there. A geometric sequence is a power, and a learning rate that halves each stage is one.

print(list(range(5, 30, 5)), list(range(20, 0, -4)))
start = 50
step = 15
print(start + step * 10)

rate = 0.1
for stage in range(4):
    print("stage", stage, "rate", rate)
    rate = rate * 0.5
print("by formula, stage 3:", 0.1 * 0.5 ** 3)
It runs right here in your browser, with nothing to install.

The count of steps starts at zero, where the term is the start itself. The loop and the formula must agree, which makes the loop a handy test of the formula.

Quick check
The start is 3, the step is 4, and the sequence stops before 20. What does this print?
print(list(range(3, 20, 4)))
  1. [4, 8, 12, 16]
  2. [3, 7, 11, 15, 19]
  3. [3, 7, 11, 15]
  4. [3, 7, 11, 15, 19, 23]
Show the answer

[3, 7, 11, 15, 19]

Start at 3 and add 4: 3, 7, 11, 15, 19. The next term, 23, is past 20, so the sequence stops.

A running total. A loop that keeps a total answers "when does the account pass $1,000?", because it keeps every total on the way, not only the last. Step through it. Watch total grow and the running list fill.

Sums, with a loop, sum() and the pairing shortcut. All three give 5,050 for the numbers 1 to 100. Pairing the first with the last gives 50 pairs of 101, so n * (n + 1) // 2 is the formula, and the general sum of an arithmetic sequence is the number of terms times (first + last) / 2.

total = 0
for n in range(1, 101):
    total = total + n
print(total, sum(range(1, 101)), 100 * 101 // 2)

Work that grows a little with every step adds up this way. Comparing each item with every item after it takes (n - 1) + (n - 2) + ... + 1 comparisons, so doubling n roughly quadruples the work.

Quick check
A loop and the formula, side by side. What does this print?
print(sum(range(1, 11)), 10 * 11 // 2)
  1. 55 55
  2. 45 55
  3. 50 55
  4. 55 110
Show the answer

55 55

range(1, 11) is 1 to 10, and those add up to 55. The formula gives the same: 10 * 11 / 2 = 55.

Drill

Jump to a term

A gym charges $40 to join and $25 each month after that. Set after_12 to the total paid after 12 months, using the formula. Then build first_six, the totals after 0, 1, 2, 3, 4 and 5 months.

start = 40
step = 25

after_12 = 0
first_six = []

print(after_12)
print(first_six)
In the lesson, your code is checked as you write it.

Counting in code. A loop inside a loop counts the multiplication rule. The standard library does the rest: math.factorial for orders, math.perm for ordered picks, math.comb for groups, and itertools.product and itertools.combinations to list them.

shirts = ["white", "blue", "green"]
trousers = ["jeans", "chinos"]
count = 0
for shirt in shirts:
    for pair in trousers:
        count = count + 1
print(count, len(shirts) * len(trousers))

import math
print(math.factorial(5), math.perm(8, 3), math.comb(49, 6))

math.perm(8, 3) is 8 * 7 * 6 = 336 podiums for three medals among eight runners. math.comb(49, 6) is the 13,983,816 tickets of a lottery that picks 6 numbers from 49.

Quick check
The inner loop starts one place after the outer loop. What does this print?
people = ["Ana", "Ben", "Cai", "Dee", "Eli"]
count = 0
for i in range(len(people)):
    for j in range(i + 1, len(people)):
        count = count + 1
print(count)
  1. 5
  2. 20
  3. 10
  4. 25
Show the answer

10

It counts each pair once: 4 pairs that start with Ana, 3 with Ben, 2, then 1. That's 10, which is also 5 * 4 / 2.

Worked example

Worked example: choosing 3 questions from 10

A teacher picks 3 of 10 questions for a quiz; the same three in another order are the same quiz. Count them by the rule, with math.comb, and by listing every group with itertools.

import itertools
import math

ordered = 10 * 9 * 8
print("by the rule:", ordered // (3 * 2 * 1))
print("math.comb:  ", math.comb(10, 3))

groups = list(itertools.combinations(range(10), 3))
print("by listing: ", len(groups), groups[0])
In the lesson you can change this and run it.

10 * 9 * 8 = 720 ordered picks, and each group of three was counted 3 * 2 * 1 = 6 times, so 720 / 6 = 120. math.comb gives 120 in one call, and itertools.combinations lists the groups: 120 of them, the first being (0, 1, 2). Three ways, one answer, so each checks the others.

Drill

How big is the sweep?

Train once for every combination of 4 learning rates, 3 batch sizes and 5 depths, 6 minutes a run. Set runs to the number of combinations with itertools.product, and hours to the total time. Build it from the lists, so it follows if a list changes.

import itertools

learning_rates = [0.1, 0.03, 0.01, 0.003]
batch_sizes = [16, 32, 64]
depths = [2, 4, 6, 8, 12]
minutes_per_run = 6

runs = 0
hours = 0

print(runs, hours)
In the lesson, your code is checked as you write it.
Drill

Teams of three

A class of 12 splits into project teams. Set ordered to the ways to pick a first, second and third person with math.perm, and teams to the number of different teams of three with math.comb.

import math

people = 12

ordered = 0
teams = 0

print(ordered, teams)
In the lesson, your code is checked as you write it.
In your own words
In your own words: how do you count groups where order doesn't matter, starting from a count where it does?

Write a sentence or two, then compare it with a good answer in the lesson.

Purpose. Two questions an engineer asks before running anything: what will it cost, and can we try every option?

What a growing chat sends. A chat app resends the whole conversation each turn, and each turn adds about 300 tokens. Turn 1 sends 300, turn 2 sends 600, and so on: an arithmetic sequence, whose sum is what you pay for.

import numpy as np

per_turn = 300
turns = 8
sent = np.cumsum([per_turn] * turns)
print(sent)
print(sent.sum(), per_turn * turns * (turns + 1) // 2)

np.cumsum is a running total in one call. Each number in sent is what one turn sends, the whole conversation so far, and their sum, 10,800, matches the formula. A 16-turn chat sends 40,800 tokens: double the turns, almost four times the tokens. That is why long conversations cost more than their length suggests.

Spaces too big to search. A reply of 10 tokens, each chosen from 50,000, can be written in about 10 ** 47 ways.

vocab = 50000
for length in [1, 2, 5, 10]:
    print(length, f"{vocab ** length:.1e}")

So programs don't list every option. They search cleverly, or they sample, and a language model learns patterns that carry over to text it hasn't seen.

Quick check
A route planner checks every possible order of 12 stops. How many orders is that?
  1. 66
  2. 144
  3. 4,096
  4. 479,001,600
Show the answer

479,001,600

12 * 11 * 10 * ... * 1 = 479,001,600. Nearly half a billion routes for twelve stops, which is why real planners don't check them all.

In your own words
In your own words: why does doubling the number of turns in a chat roughly quadruple the tokens sent?

Write a sentence or two, then compare it with a good answer in the lesson.

Goes deeper in

Practice what you just read

  • 6 code examples you can edit and run
  • a practice exercise that checks your code
  • a 6-question quiz
  • 10 review cards for spaced repetition

Try a quiz question

Which of these sequences is geometric?

  1. 5, 15, 45, 135
  2. 5, 15, 25, 35
  3. 5, 10, 20, 35
  4. 5, 4, 3, 2

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 0 · about 32 hours of study

Tools

Python, the terminal and calling APIs 46 lessons All free
  1. Your first program FreeRun Python, print output, and read an error message without panicking.24 min
  2. Typing code exactly FreeBrackets, quotes, indentation and the look-alike characters that stop a program.26 min
  3. Variables FreeGive values names so your program can remember and reuse them.24 min
  4. Numbers and arithmetic FreeIntegers, decimals, rounding, and the math behind every metric.30 min
  5. Strings and f-strings FreeWork with text: join it, slice it, clean it, and format it.30 min
  6. Decisions with if/else FreeCompare values and choose what happens next.35 min
  7. Fractions, ratios and rates FreeShares, rates, percentage points and ratios, with Python doing the arithmetic.35 min
  8. Ranges and edges in code FreeAt least, under and between as symbols; intervals with each end in or out; bands with no gaps.32 min
  9. Lists FreeKeep many values in order, then index, slice and change them.28 min
  10. Files, folders and paths FreeWhat a file's name tells you, paths as directions through folders, and where a relative path starts.30 min
  11. Loops FreeRepeat work over every item without copy-pasting code.35 min
  12. Formulas: order, powers and rearranging FreeWork a calculation in the right order, fill in a formula, and turn it around to find what's missing.24 min
  13. Loops that add and count: sequences, sums and combinations FreeSequences that add or multiply each step, a formula for any term, and adding a sequence up.34 min
  14. Dictionaries FreeLook values up by name: the shape of almost all real-world data.40 min
  15. Functions FreePackage steps into reusable, testable pieces with inputs and outputs.35 min
  16. While loops FreeRepeat until something changes: goals reached, answers valid, tasks done.38 min
  17. Functions as values FreeStore functions, pass them in with key=, and accept any number of arguments.40 min
  18. Comprehensions FreeFilter and transform a whole collection in one readable line.38 min
  19. Errors and exceptions FreeRead tracebacks, and handle the failures you expect.38 min
  20. Finding bugs when nothing crashes FreeA method for wrong answers: expected against actual, reproduce, look inside, fix one thing.36 min
  21. Sets: unique items and fast lookups FreeDuplicates, fast membership, set operations and comparing two lists.34 min
  22. Modules and imports FreeUse Python's standard library instead of reinventing it.38 min
  23. Classes and objects FreeBundle data with the functions that work on it.38 min
  24. Inheritance and class attributes FreeBuild classes on other classes, and share values across every object.35 min
  25. Review: find the slip (Python core) FreeTen slips that run without an error, found by working a tiny input by hand, and the construct sheet for NumPy and PyTorch code.30 min
  26. JSON FreeThe text format APIs and LLMs use to exchange structured data.34 min
  27. Files and CSV data FreeRead and write files, and turn a spreadsheet export into Python data.33 min
  28. NumPy arrays FreeDo math on whole columns at once, the foundation of every ML library.30 min
  29. NumPy in practice: shapes, types and picking values FreeReshape, view and copy, where and clip, top-k, stacking and the (N, C, H, W) batch a model expects.35 min
  30. DataFrames with pandas FreeLoad a table, pick rows and columns, and summarize groups in a few lines.40 min
  31. Charts with Matplotlib FreeLine, bar, scatter, histogram and box plots, labeled and honest.42 min
  32. Project: images are arrays FreeGray, crop, brighten, watermark and palette tools built on NumPy and Pillow.45 min
  33. The terminal FreeNavigate folders and run programs by typing commands.30 min
  34. Version control with git FreeSave snapshots of your work, undo mistakes, and share code.30 min
  35. Packages and environments FreeInstall libraries with pip and keep projects isolated with venv.25 min
  36. Python on your own computer FreeInstall Python and VS Code, make a virtual environment, then run, debug and test a project.45 min
  37. How APIs work FreeRequests, responses, methods, status codes and headers.30 min
  38. Calling APIs from Python FreeSend requests, read JSON responses, and handle failures.35 min
  39. API keys and secrets FreeAuthenticate safely and keep keys out of your code.25 min
  40. Your first LLM call FreeSend messages to a model and read its reply, tokens and stop reason.30 min
  41. Capstone: ad-copy reviewer FreeCombine files, functions, JSON and an LLM call into one small tool.40 min
  42. Dates, times and time zones Freedatetime, timedelta, formats, time zones and the traps when clocks change.42 min
  43. Regular expressions FreeFind, check, extract and clean text patterns with the re module.42 min
  44. Sending email and text messages FreeEmailMessage, smtplib, mail merge and an SMS API, with secrets kept out of code.42 min
  45. Web pages: HTML and CSS FreeRead and write HTML, what forms send, CSS selectors and escaping.42 min
  46. Scraping web pages FreeBeautiful Soup, one record per item, pagination and robots.txt.45 min

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write