Reading Kattis Input

These are common ways Kattis problems provide input.

All examples use sys.stdin.readline(), which is faster and preferred for competitive programming.

Make sure to use

import sys

1. Single Integer

Example Input

7

Python

import sys
n = int(sys.stdin.readline())

2. Two Integers on One Line

Example Input

3 5

Python

import sys
a, b = map(int, sys.stdin.readline().split())

3. Multiple Integers on One Line (Unknown Count)

Example Input

5 12 19 3 8

Python

import sys
nums =  [int(x) for x in sys.stdin.readline().split()]

4. N Followed by N Numbers

Example Input

4
10
20
30
40

Python

import sys
n = int(sys.stdin.readline())
vals = [int(sys.stdin.readline()) for _ in range(n)]

5. Read Until EOF (No Count Given)

Example Input

3 4
7 8
10 2

Python

import sys

# Reads all remaining input until EOF
for line in sys.stdin:
    n,m=map(int, line)



6. Grid Input (R rows × C columns)

Example Input

3 4
abcd
efgh
ijkl

Python

import sys
R, C = map(int, sys.stdin.readline().split())
grid = [list(sys.stdin.readline().strip()) for _ in range(R)]

7. Mixed Types on a Line

Example Input

alice 23 5.7

Python

import sys
name, age, height = sys.stdin.readline().split()
age = int(age)
height = float(height)

8. Repeated Cases Until Sentinel Value

Example Input

5
3
1
0

Python

import sys

while True:
    x = int(sys.stdin.readline())
    if x == 0:  # sentinel value
        break
    # process x