Python on the SOI Grader

Written by Joël Benjamin Huber.

General Remarks

Python is supported for the finals and team selection of SOI even though it is not supported at IOI. We guarantee that all tasks from the finals can be solved for 100 points using Python.

To submit Python to the SOI Grader, there are a few points to consider:

  • As Python is generally slower and uses more memory than C++, Python submissions will have four times the time and two times the memory available. If, for example, it says on some task “Time limit: 1000ms, memory limit: 256MiB”, then Python will have a time limit of 4000ms and memory limit of 512MiB.
  • The “Python” interpreter (CPython) can be slow and might get you TLE, whereas PyPy runs significantly faster. We recommend you to choose “Pypy” instead of “Python” from the languages-menu when submitting Python code. (PyPy is just a different interpreter for the Python language, and you likely don’t need to change anything in your code).
  • For faster input, you should use stdin.readline() instead of input() (where you need to import stdin first, you can do this with from sys import stdin first)
  • Python has a built-in recursion limit of 1000, which can be too low if you’re coding something recursively. You can increase it by using “sys.setrecursionlimit(10**5)” (where 10**5 is number of recursive calls you want to support). You need to add import sys at the top of your file. If you set the recursion limit to a too large number, your program crashes at the start and produces wrong answer.
  • Recursion in Python is quite slow. Sometimes it might be necessary to rewrite a recursive function into an iterative one in order to pass the timelimit.

Patterns

Below you can find some often used patterns when implementing your solutions in Python.

Reading input

a = int(input())  # One integer on a line
a, b, c = map(int, input().split())  # Multiple integers on a line
a = list(map(int, input().split()))  # List of integers on a line

Printing output

print(a)  # Print one value on a line
print(a, b, c)  # Print multiple values on a line, separated by space
print(*a)  # Print list of values on a line, separated by space

Faster input

In case your code times out but the time complexity should be correct.

In addition, make sure to submit using PyPy instead of Python, when selecting the language.

from sys import stdin
input = stdin.readline

Increased recursion limit

import sys
sys.setrecursionlimit(10**5)