User Tools

Site Tools


python3:input_output

This is an old revision of the document!


Input and Output

There is no magic bullet that leads to the fastest input and output in a programming contest. Having said this, there are typically multiple ways of performing and processing input and output in Python3. By understanding the options that are available and how to optimize them (e.g., conducting tests) you can see a real world performance increase, in particular when faced with high volumes of reads and writes.

Input Basics

Input in Python3 is handled via the input() function, and reads a newline-terminated string from standard input.1) Additional processing is done to the resulting string.

>>> x = input()
Hello World! # x="Hello World!"
>>> x = int(input())
42 # x=42
>>> x = input().split()
Hello World! # x=["Hello", "World!"]
>>> (x, y) = map(int, input().split())
1 2 # x=1, y=2

map() applies a function across a sequence or iterable structure. The comma , unpacks the map object into x and y.

>>> x = list(map(float, input().split()))
1.2 2.3 3.4 4.5 # x=[1.2, 2.3, 3.4, 4.5]

Output Basics

Output is handled with the print() function.

>>> print() # '\n'
>>> print("Hello World!") # "Hello World!\n"
>>> print("Hello", "World!") # "Hello World!\n"
>>> print(1, 2, 3, sep='') # "123\n"
>>> print(1, 2, 3, end='-')
>>> print("a b c") # "1 2 3-a b c\n"

Advanced Options

Like the interpreted semantics of Python3, input() and print() are slow compared to their C++ and Java counterparts. The sys library provides faster counterparts.

<code python>

<code python>

Benchmarks

n input() sys.stdin.readline() sys.stdin.readlines()
104 .034 .016
105 .146 .052
106 1.301 .301
input.py
num_lines = int(input())
 
for i in range(num_lines):
    line = input()
readline.py
from sys import stdin
 
num_lines = int(input())
 
for i in range(num_lines):
    line = stdin.readline()
read_test.py
from sys import argv
from random import *
from string import *
 
for i in range(int(argv[1])):
    print(''.join(choice(ascii_lowercase + ' ') for _ in range(int(argv[2]))))

2) 3)

1)
Unlike C++ and Java, input is line-based rather than token-based.
2)
python3 read_test.py 1000 10 > out.txt
3)
python3 read_test.py 1000 1000 > out.txt
python3/input_output.1534274351.txt.gz · Last modified: 2018/08/14 14:19 by kericson