Start free

Intermediate · Nested loops · 122 of 264

Pairs that add up

Count the pairs of positions (i < j) whose numbers add up to a target.

Input: whole numbers on one line, then the target on the next line. Output: the number of pairs.

Examples

Input
1 2 3 4 5
5
Output
2
Input
1 1 1
2
Output
3
Input
3 7
11
Output
0

One more test checks other inputs when you press Check.

Stuck? The idea behind nested loops

A loop inside a loop: for each turn of the outer loop, the inner one runs all the way through. Good for rows and columns.

print(..., end="") stays on the same line; an empty print() after the inner loop moves to the next row.

for row in range(1, 4):
    line = []
    for col in range(1, 4):
        line.append(str(row * col))
    print(" ".join(line))

Watch for: print(x, end=" ") leaves a space at the end of every line, and the tests see it. Build each line as a list and print " ".join(line): spaces only between.

All the nested loops exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More nested loops exercises