Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Everyone shakes hands

At a party, everyone shakes hands with everyone else, once. How do you count the handshakes? Take the first person, and they shake hands with each of the others. Then take the second person, and so on.

In code, that's a loop inside a loop. The outer loop picks a person. The inner loop goes through the people they shake hands with. For every single pass of the outer loop, the inner loop runs all the way through from start to finish.

The inner loop runs in full: for every pass of the outer loop.

Start the inner loop later

If the inner loop also started from the first person, you would count a person shaking hands with themselves, and every handshake twice, once from each side. That's wrong.

The fix: the inner loop starts just after the outer person. Person 1 meets 2, 3, 4, and so on. Person 2 meets 3, 4, and so on, because they already met 1. Each pair then appears exactly once, with the smaller number first.

Inner loop starts after the outer, so each pair is counted once.
In code
count = 0
for a in range(1, n + 1):
    for b in range(a + 1, n + 1):
        if a + b == total:
            count = count + 1
Pairs from 1 to 5 that add up to 6
1
0
2
1
3
2
4
3
5
4
ab
a
1
b
2
count
0

The outer loop picks a = 1. The inner loop starts after it, at b = 2. 1 plus 2 is 3, not 6.

Move 1 of 5