09-21

Reading

You need to convert strings to numbers with the int function.

  • Read a single number: int(input())
  • Read a list of numbers: [int(n) for n in input().split()]

If different items in the list have different meanings, it can be useful to give them all variable names in the assignment:

[a,b,g] = [int(n) for n in input().split()]

Files

The second argument of the open controls whether the file is read or written. There are other modes but they are not useful in the kinds of work we will be doing.

  • Open for reading: infile = open("filename.in","r")
  • Open for writing: outfile = open("filename.out","w")
  • Close when done: outfile.close()
Standard I/O File I/O
input() infile.readline()
print() print(..., file=outfile)
outfile.close()

The standard approach to a USACO contest problem is to use files as explained above. There is a trick you can use to make very few changes to use files.

Get your program working using print and input. When you are satisfied it works, swap the default input and output so they go to files.

import sys
sys.stdin = open("usaco.in", "r")
sys.stdout = open("usaco.out", "w")

You may need to add sys.stdout.flush() at the end of your program if output does not show up in the file.

Practice

  • USACO 2019 February Bronze 1 and 2 (revegetation).