Join an online judge with Python 3.x

I think there are people who are doing competitive programming and online judges for various reasons, such as keeping the motivation to study the program and conversely seeking a place to put what they have learned into practice. Now that there are many sites, it's easy to enjoy at your own pace and ability. If you are interested, I will link to the following article for reference.

This time as well, I would like to help lower the hurdles for participating in online judges (in terms of I / O) as well as serving as a memorandum.

1 Do you use Python 3.x?

I'm likely to be told, so please decline first. Basically, online judges should use a programming language that they are familiar with and that is compatible with it. Most of the time, you will use C (++), and if you want the calculation speed, it is better. On the other hand, there will be a certain number of people who have experience in programming who use Python, and recently, considering that there are abundant libraries including artificial intelligence, there are also people who have entered the world of programming via Python. I think. When such people think, "Let's study various things as an online judge," I think that I / O will be difficult at first. I'm still struggling.

Of course, there are also pioneers who have written the following articles.

I am also indebted to you, but it seems that the grammar is as old as 2.x. So I decided to write an article for 3.x. I hope it will be helpful for the participants.

2 input

1: One thing in one line

input


X

python


var = input()

This will assign X to the variable var. In this case, the variable is assigned as a character string, so if necessary, operations such as `ʻint (input ()) and float (input ()) `` are required.

2: Multi-line input

In online judges, the format may be the number of data on the first line and the input data on the second and subsequent lines. In that case, it will be easier to handle in Python if you input in list format.

input


5 #Number of data N
1
2
3
4
5

python


n = int(input())
a = [input() for i in range(n)]

The value is now assigned to a in list format. However, it is also in string format here. As we will see later in the output, it is better to consider whether the variable type in the list is an integer, a floating point number, or a string as needed.

In the article introduced above, the input is `raw_input ()`, but this is from the 2.x era, and in 3.x it is integrated into input ()` ``. It seems that it was done. From now on, let's use input () `` `.

3: Assign multiple values in one line

This is also common in online judges' input formats. I think there are two patterns of this kind, so let's look at each one.

When assigning to multiple variables

For example, if you want to assign to multiple variables in a format like a b ... `` `, use map```. For example, if you want to store 3 integers.

input


#Example array
1 2 3

python


a, b, c = map(int, input().split())

This will substitute a = 1, b = 2, c = 3 without any problem. In this regard,

Tips (input / output) you should know when programming in Python

If the number of elements in the list matches the number on the left side, each element in 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.

Is written. Let's make great use of it that way.

When you want to handle a series of data like an array

Of course, to treat it like an array in Python, we use a list. However, unlike the 2.x era, the grammar used just above does not work for 3.x. Let's take a look at this for a moment.

python


a = map(int, input().split())

In the 2.x era, it seems that it was valid to read input ()` `` as `` `raw_input ()` ``. However, since 3.x, map``` is treated as an object, so if you try to treat it as it is like a list, an error will occur.

For example, a = ["2", "1", "3"] `` `, and you want to sort, consider the following if``` statement.

error


if int(a[i]) < int(a[j]):
    #Some processing

However, think of i, j as counter variables. It's an example of sorting ... Then you will probably get an error like this:

consoleout


TypeError: 'map' object is not subscriptable

This is, without fear of misunderstanding, that `map``` and list``` are of different types. The solution to this problem is to type `` map to `` `list. That is, do the following:

python


a = list(map(int, input().split()))

This solved it.

3 output

1: One variable with line breaks

You can use `` `print``` normally. It has been said many times when the system changed from 2.x to 3.x, but don't forget the parentheses.

python


print(a) #Output the value of variable a

2: Multiple variables with line breaks

This just lists multiple variables with print.

python


print(a,b,c)

It is automatically output with a single-byte space separated by one character.

3: I want to convert the list to an integer and output it side by side

Perhaps this will be the highlight. If you don't get used to it, you will probably have a hard time. This is easy to understand using join. In the following example, numbers from 0 to 4 are output separated by half-width spaces.

python


a = [str(i) for i in range(5)] #Dare here"String"List 0-4 as
print(" ".join(a)) #Half-width space delimiter
# -> 0 1 2 3 4

However, you need to be careful at this stage as I wrote earlier. joinIs that the argument can only be used for string types. This is an integerintWhat happens then?

python


a = [int(i) for i in range(5)] #Originally unnecessary, but to specify it, add int to list 0-4
print(" ".join(a)) #I want to output separated by half-width spaces
# -> TypeError: sequence item 0: expected str instance, int found

Will result in an error. Also, if the type is output as "character string", Runtime Error may be returned depending on the discriminator. This is a blind spot when debugging in the console. If the algorithm or output format looks correct but doesn't work, you should be aware of this as well.

(Added on May 28, 2017) From @ shiracamus's comment

If you want to output str, int, whatever, separated by half-width spaces, you can write as follows.

a = [1, 'abc', 2.34, 5+6j]
print(*a)
#-> 1 abc 2.34 (5+6j)

I think it's smart because you don't have to think about the type as in the text. It was helpful, thank you.

4: I want to specify the format

From Python 3.x, the `` `format``` format is recommended over the C-like% notation. You may not have noticed it so much in the Python system, but it will be effective when the judge who allows the calculation error below a certain level or when the output is specified. Or rather, it wouldn't be accepted otherwise.

python


a = 10
b = 1.234567
print("Example: a={:05d}, b={:.3f}".format(a,b))
#-> Example: a=00010, b=1.235

If you forget the colon in {}, you will get angry. Let's be careful. formatFor more information, please search or read the reference.

in conclusion

I wrote it briefly, but I think that if you know this much, it will be useful in combination. Please comment if anything is missing. Have a good programming life!

Recommended Posts

Join an online judge with Python 3.x
x86 compiler self-made with python
Create an LCD (16x2) game with Raspberry Pi and Python
Cut out an image with python
Create an Excel file with Python3
I sent an SMS with Python
[Python] Send an email with outlook
[Python] Building an environment with Anaconda [Mac]
Note when creating an environment with python
Quickly create an excel file with Python #python
I tried sending an email with python.
[Python] Quickly create an API with Flask
Scraping from an authenticated site with python
Create an English word app with python
Send an email with Amazon SES + Python
Installing PIL with Python 3.x on macOS
Light image processing with Python x OpenCV
Let's develop an investment algorithm with Python 1
[Blender x Python] Let's get started with Blender Python !!
FizzBuzz with Python3
Scraping with Python
Statistics with python
Create an app that guesses students with python
[Python] Make a game with Pyxel-Use an editor-
Scraping with Python
Send an email to Spushi's address with python
Let's write FizzBuzz with an error: Python Version
[Python] Clustering with an infinitely mixed Gaussian model
Twilio with Python
How to crop an image with Python + OpenCV
GUI automation with Python x Windows App Driver
Integrate with Python
Play with 2016-Python
AES256 with python
python starts with ()
Create an image with characters in python (Japanese)
Put Python 2.7.x on Mac OSX 10.15.5 with pyenv
[Blender x Python] How to make an animation
Bingo with python
Zundokokiyoshi with python
Install shogun with python modular (OS X Yosemite)
Send an email with Excel attached in Python
Post an article with an image to WordPress with Python
Create an API server quickly with Python + Falcon
[Blender x Python] Think of code with symbols
Excel with Python
Microcomputer with Python
Cast with python
I tried to build an environment for machine learning with Python (Mac OS X)
code-server online environment (3) Launch an EC2 instance with Boto3
Reading Note: An Introduction to Data Analysis with Python
Building an environment for natural language processing with Python
Serial communication with Python
Django 1.11 started with Python3.6
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Learning Python with ChemTHEATER 03