Basics 0/97

Loops and simulation · 1 of 2

Basic syntax and I/O

Read a judge's input, print the answer in the layout it expects, write loop bounds that are not off by one, and keep numbers in a type large enough for them.

4,133 words · 19 min read

Part 1 of 9 Input and output on a judge

Standard input and output

Every problem in this course is checked by a judge, a program that runs our solution on tests we do not get to see and compares what it prints with the expected output. So before any algorithm, a solution has to read the input in the layout the statement describes, print the answer in the layout the statement asks for, loop over exactly the right positions, and keep its numbers in a type that is large enough. This lesson is about those parts of a program.

We will use one small task for most of the lesson. A sensor took nn readings, and we want to count the readings that are at least a threshold tt. The first line of the input holds nn and tt, and the second line holds the nn readings:

5 64 8 2 8 6
Input

The readings that are at least 6 are the two 8s and the final 6, so the program should print:

3
Output

On Codeforces, AtCoder, CSES and newer USACO problems, the input arrives on standard input, which is what input() reads, and the answer goes to standard output, which is where print writes. The whole program is:

Sign up to run
n, t = map(int, input().split())
readings = list(map(int, input().split()))
count = 0
for value in readings:
    if value >= t:
        count += 1
print(count)

On the input above, the program prints 3.

input() returns the next line of the input as a string, here "5 6". .split() cuts that string at its spaces into the pieces "5" and "6", and map(int, ...) turns each piece into an integer, so the first line of the program sets n to 5 and t to 6. The second line reads the readings the same way and keeps them in a list. input() reads one line at a time, so the program calls it once for each line the statement describes. The loop never uses n, because the list knows its own length, but n still has to be read: it shares a line with t.

The comparison is >= because the statement says “at least”, which includes a reading equal to the threshold. With > the program would miss the final 6 and print 2.