Tips (input / output) that you should know when programming competitive programming with Python2

The input / output part of tips you should know when programming in Python2 has been split.

The input / output method for competitive programming in Python is illustrated. Input / output codes are often a hurdle when learning a language for the first time, but once you remember it, it's a pattern, so you want to remember it quickly.

The Python version is ** 2.7.5 ** (Python3 has very different specifications such as input / output, so it is recommended to refer to other articles).

reference

Receiving standard input 1-Qiita

Input one string per line

format

input


S

S is a character string.

input

S = raw_input()

Input one integer or one floating point number on one line

format

input


N

N is an integer or floating point number.

input

N = input()

Enter multiple strings separated by spaces on one line

format

input


A B C

A, B, and C are all character strings.

input

l = raw_input().split()
print l[0] #The value of A is output
print l[1] #The value of B is output
print l[2] #The value of C is output

split () splits the string into a list separated by spaces.

Enter multiple integers or floating point numbers separated by spaces on one line

format

input


A B C

A, B, and C are all integers or floating point numbers.

input

When you want to assign all variables to a list

If A, B, and C are all integers,

l = map(int, raw_input().split())
print l[0] # A
print l[1] # B
print l[2] # C

In short, the input received in the string type is divided by spaces and assigned to the list, and each element is mapped to the integer type.

The number of elements may be given to the input data, but in the case of Python it does not matter much even if it is not used.

For floating point numbers

l = map(float, raw_input().split())

Note that if you use ʻint` for floating point numbers, the value will be truncated.

If you want to store each in a separate variable

A, B, C = map(int, raw_input().split())
print A # A
print B # B
print C # C

If the number of elements in the list matches the number on the left side, each element of the list can be assigned to each variable on the left side. It seems that this type of assignment is called "unpacked assignment".

In the case of competitive programming, it should be used only when the number of input elements is clear and small.

Although it is rarely seen, if a character string or an integer is mixed in one line, one line is received as a character string for the time being, and later converted using ʻint () , float () `, etc.

Enter one integer for each of multiple (N) rows

format

input


N
a1
a2
a3
...
aN

a1, a2, ..., aN are N integers.

input

N = input()
a = []
for i in range(N):
    a.append(input())
print a # [a1, a2, a3, ..., aN]

It's OK.

@ zakuro9715 taught me.

This code can also be expressed as follows using list comprehension notation. N-line input can be written in one line and is beautiful.

N = input()
a = [input() for i in range(N)]
print a # [a1, a2, a3, ..., aN]

Enter one integer for each of multiple lines (until a specific integer is accepted)

Aizu Online Judge (AOJ) A format often seen.

format

input


a1
a2
a3
...
-1

a1, a2, ..., are all integers. -1 represents the end of input.

input

a = []
while True:
    n = input()
    if n == -1:
        break
    a.append(n)
print a # [a1, a2, a3, ..., aN]

Input one integer for each of multiple lines (until the end of input)

I also see this occasionally on AOJ. It's hard to debug, and I personally hate it.

format

input


a1
a2
a3
...
(EOF)

a1, a2, ..., are all integers. Read until EOF comes.

input

import sys

a = []
for line in sys.stdin:
    a.append(int(line))
print a # [a1, a2, a3, ...]

Input of M integers in each of multiple (N) lines

A summary feeling so far.

format

input


N M
a11 a12 a13 ... a1M
a21 a22 a23 ... a2M
a31 a32 a33 ... a3M
...
aN1 aN2 aN3 ... aNM

a11, a12, ..., aNM are integers.

input

N, M = map(int, raw_input().split())
a = []
for i in range(M):
    a.append(map(int, raw_input().split()))
print a 
# [[a11, a12, a13, ..., a1M]
#  [a21, a22, a23, ..., a2M]
#  ...
#  [aN1, aN2, aN3, ..., aNM]]

Maybe it's okay if you keep this down.

General purpose input using a generator

I learned from @ t2y.

By using a generator, it is possible to receive input over multiple lines well.

For example

format

input


a1
a2
a3
...
(EOF)

a1, a2, ..., are all character strings. Read until EOF comes.

If the format is like

def get_input():
    while True:
        try:
            yield ''.join(raw_input())
        except EOFError:
            break

if __name__ == '__main__':
    a = list(get_input()) # [a1, a2, a3, ...]

To do.

Besides, the contents of get_input (),

def get_input():
    while True:
        try:
            s = raw_input()
            if s == '-1':
                break
            yield ''.join(s)
        except EOFError:
            break

By changing to, it is possible to receive a slightly complicated input such as "read" -1 "or until the end of input".

output

Output 1 variable (with line break)

format

output


A

Includes a line break at the end.

output

print A

Both integer type and character string type can be output. In addition, debugging of lists and dictionaries can be done as it is with the print statement.

Output 1 variable (no line break)

To be honest, I haven't seen it, but for the time being, for studying.

format

output


A

Does not include line breaks at the end.

output

import sys

sys.stdout.write(A)

Output multiple variables separated by spaces

I often see this.

format

output


A B C

Includes a line break at the end.

output

print A, B, C

In the print statement, if you put , after the variable, the line break will be converted to a half-width space.

Python Tips: I want to output a character string without line breaks --Life with Python

Output multiple variables separated by commas

format

output


A,B,C

A, B, and C are all character strings. Includes a line break at the end.

output

print ','.join([A, B, C])

join () corresponds to the inverse operation of split () and returns the concatenation of each element of the argument string list with the receiver string.

Note that all elements of the list must be of type string.

Here, for example, if A, B, and C are integers,

print ','.join(map(str, [A, B, C]))

Like, after converting each element to a character string by str (), join.

Output according to format

There are cases where you want to output in a free format, such as the printf function in C ++.

Format (example)

output


Case 1: A B

Both A and B are integers. Includes a line break at the end.

output

print 'Case 1: {0} {1}'.format(A, B)

format () takes a variadic argument and returns a string containing the value of the i-th argument in'{i}'.

You can do most of the things you can do with printf, such as radix conversion and digit alignment at the time of output, with format (). For details, see Reference.

Recommended Posts

Tips (input / output) that you should know when programming competitive programming with Python2
Tips you should know when programming competitive programming with Python2
Tips (control structure) that you should know when programming competitive programming with Python2
Tips (data structure) that you should know when programming competitive programming with Python2
Tips you should know when programming competitive programming with Python2 (useful library)
Tips to know when programming competitively with Python2 (Other language specifications)
Competitive programming with python
Python3 standard input for competitive programming
Tips on Python file input / output
Input / output with Python (Python learning memo ⑤)
Knowledge of linear algebra that you should know when doing AI
Competitive programming with python Local environment settings
I made a competitive programming glossary with Python
Personal tips when doing various things with Python 3
[python] [vscode] When you get angry with space-tab-mixed
Solve with Python [100 past questions that beginners and intermediates should solve] (053 --055 Dynamic programming: Others)
You should know if you use Python! 10 useful libraries
What are you using when testing with Python?
[Python] Building an environment for competitive programming with Atom (input () can be used!) [Mac]
Japanese output when dealing with python in visual studio
3. 3. AI programming with Python
Competitive programming diary python 20201213
Python programming with Atom
python input and output
Python audio input / output
Competitive programming diary python 20201220
Competitive programming diary python
Programming with Python Flask
I know? Data analysis using Python or things you want to use when you want with numpy
[Tips] Dealing with errors that occur when trying to install Python 3 series less than 3.5.3 with pyenv
Solution when you want to use cv_bridge with python3 (virtualenv)
Use a macro that runs when saving python with vscode
Programming with Python and Tkinter
Try Python output with Haxe 3.2
I tried to find out as much as possible about the GIL that you should know if you are doing parallel processing with Python
Receiving standard input tips @ python
[Tips] Handle Athena with Python
Python Competitive Programming Site Summary
Error when playing with python
Network programming with Python Scapy
If you know Python, you can make a web application with Django
When you want to print to standard output with print while testing with pytest
When you run diff in python and want both returncode and output
Input / output method of values from standard input in competitive programming, etc.
Solve with Python [100 selections of past questions that beginners and intermediates should solve] (034-038 Dynamic programming: Knapsack DP basic)
Solve with Python [100 selections of past questions that beginners and intermediates should solve] (039 --045 Dynamic programming: Knapsack DP variant)