[Python] Basic knowledge used in AtCoder

AtCoder beginners can solve problems Make a note of the knowledge that may be useful.

input

Receive various inputs.

Receiving letters

S = input()

Receiving numbers

N = int(input())

Receiving blank numbers

A,B = map(int,input().split())

Receive the number of inputs and receive the number of inputs Writing using square brackets is called "inclusive notation"

N = int(input()) #Number of inputs
l = list(int(input()) for _ in range(N)) #Get N numerical inputs as a list
#Or
l = [int(input()) for _ in range(N)] #Get N numerical inputs as a list

Receives the number of inputs and receives blank numbers for that number of times

Q = int(input())
L = [0]*Q
R = [0]*Q

for i in range(Q):
    L[i], R[i] = map(int, input().split())

#Or
l = list(list(map(int, input().split())) for _ in range(Q))
l = [list(map(int,(input().split()))) for _ in range(Q)]

If you want to change the string later, take it as a list of characters

Python #input
T = list(input())
T[0] = "p"
print("".join(T))
python

output

Output list with blanks

l = [1,2,3]
print(*l)
1 2 3

Output list without whitespace join

l = [1,2,3]
l = map(str,l) #Since join is for a string, convert it to a string
print("".join(l))
123

format

name = "Suzuki"
height = 170
weight = 60

print("{0}Is tall{1}cm, weight{2}kg".format(name,height,weight))
Mr. Suzuki is 170 cm tall and weighs 60 kg.

Repeating strings, multiplying strings

s = "Python"
print(s*3)
PythonPythonPython

Ternary operator

flag = 1

print("Yes" if flag else "No")
print("Yes" if not flag else "No")
Yes
No

Calculate formula from string eval

print(eval("1+2"))
3

Sum of each digit

Convert a number to a character string and decompose it into numbers of each digit to find the sum

x = 1357

sum(int(i) for i in str(x))
#Or
sum(list(map(int, str(x))))

Absolute value

abs(-2)

Merchandise and remainder

x = 10; y = 3

q = x // y
mod = x % y
q, mod = divmod(x, y)

list

sort Sort in descending order

l = [1,3,5,2,4]

l.sort()
l2 = sorted(l) #Put in another variable

l.sort(reverse = True) #Sort in descending order
l2 = sorted(l, reverse = True) #Sort in descending order and put in another variable

Sort by second element

l = [[1,5],[2,2],[3,4]]

l.sort(key=lambda x:x[1])
print(l)
[[2, 2], [3, 4], [1, 5]]

Slice operation Output list in reverse order

l = [1,2,3,4,5]
print(l[2:]) #Second and subsequent
print(l[:2]) #Up to the second
print(l[2:4]) #From 2nd to 4th
print(l[-2:]) #Two from the back
print(l[::-1]) #Output list in reverse order
print(l[::2]) #Skip one
print(l[1::2]) #Skip one after the second
[3, 4, 5]
[1, 2]
[3, 4]
[4, 5]
[5, 4, 3, 2, 1]
[1, 3, 5]
[2, 4]

enumerate Get list index and element at the same time

l = ["National language","Math","Science","society","English"]

#The second argument is the start index
for i,subject in enumerate(l, 1):
    print(str(i)+"The second is"+subject)
The first is the national language
The second is mathematics
The third is science
Fourth is society
5th is english

Greatest common divisor, least common multiple

from fractions import gcd

x = 8
y = 12

gcd(x,y) #Greatest common divisor
(x*y)//gcd(x,y) #Least common multiple

Permutations, combinations

from itertools import permutations, combinations

balls = [1, 2, 3]
print(list(permutations(balls, 3)))  #permutation
print(list(combinations(balls, 2)))  #combination
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
[(1, 2), (1, 3), (2, 3)]

ASCII code ord, chr

【ord】 Convert to ASCII code 【chr】 Convert ASCII code to characters

151 A - Next Alphabet コメント 2020-02-08 172153.png

c = input()
print(chr(ord(c) + 1))

Primality test

To determine the prime number, check if there is a number divisible up to $ \ sqrt {n} $.

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

Distance between two points

import numpy as np

a = np.array((1,2))
b = np.array((5,6))

distance = np.linalg.norm(a-b)

Initialization at infinity

f_inf = float('inf')
f_inf_minus = -float('inf')

Remove duplicate values

l = [4,2,1,3,4,3,2]

print(set(l))
{1, 2, 3, 4}

Check the number of occurrences of the alphabet

import string

val_str = "hello everyone"

d = {}

alphas = string.ascii_lowercase
for key in alphas:
    d[key] = 0

for key in val_str:
    if key in alphas:
        d[key] += 1

for i in d:
    print("{0} : {1}".format(i,d[i]))
a : 0
b : 0
c : 0
d : 0
e : 4
f : 0
g : 0
h : 1
i : 0
j : 0
k : 0
l : 2
m : 0
n : 1
o : 2
p : 0
q : 0
r : 1
s : 0
t : 0
u : 0
v : 1
w : 0
x : 0
y : 1
z : 0

When examining only what appears

import string
from collections import defaultdict
val_str = "hello everyone"

d = defaultdict(int)

for key in val_str:
    d[key] += 1

for i in d:
    print("{0} : {1}".format(i,d[i]))
h : 1
e : 4
l : 2
o : 2
  : 1
v : 1
r : 1
y : 1
n : 1

2 minutes search

146 C - Buy an Integer image.png

A,B,Z = [int(i) for i in input().split()]

max = 10 ** 9 + 1
min = 0

while max - min > 1:
    avr = (max + min) // 2
    sum = A * avr + B * len(str(avr))
    if sum <= Z:
        min = avr
    else:
        max = avr

print(min)

Output index in order of score

Output using a dictionary (dict)

l = [7,6,13,10,7]

dic = {}
for i,score in enumerate(l):
    dic[i+1] = score

dic = sorted(dic.items(), key=lambda x:x[1], reverse = True)

for i in dic:
    print("{0}, score:{1}".format(i[0],i[1]))
3, score:13
4, score:10
1, score:7
5, score:7
2, score:6

On the contrary, the ranking is output

l = [7,6,13,10,7]
l2 = sorted(l, reverse = True)

for i in l:
    print(l2.index(i) + 1)
3
5
1
2
3

Recommended Posts

[Python] Basic knowledge used in AtCoder
Daily AtCoder # 36 in Python
Daily AtCoder # 2 in Python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Daily AtCoder # 53 in Python
Daily AtCoder # 33 in Python
Daily AtCoder # 7 in Python
Daily AtCoder # 24 in Python
Daily AtCoder # 37 in Python
Daily AtCoder # 8 in Python
Daily AtCoder # 42 in Python
Basic sorting in Python
Daily AtCoder # 21 in Python
Daily AtCoder # 17 in Python
Daily AtCoder # 38 in Python
Daily AtCoder # 54 in Python
Daily AtCoder # 11 in Python
Daily AtCoder # 15 in Python
Daily AtCoder # 47 in Python
Daily AtCoder # 45 in Python
Daily AtCoder # 30 in Python
Daily AtCoder # 40 in Python
Daily AtCoder # 10 in Python
Daily AtCoder # 5 in Python
Daily AtCoder # 28 in Python
Daily AtCoder # 39 in Python
Daily AtCoder # 20 in Python
Daily AtCoder # 19 in Python
Daily AtCoder # 52 in Python
Daily AtCoder # 3 in Python
Daily AtCoder # 14 in Python
Daily AtCoder # 50 in Python
Daily AtCoder # 26 in Python
Daily AtCoder # 4 in Python
Daily AtCoder # 43 in Python
Daily AtCoder # 29 in Python
Daily AtCoder # 22 in Python
Daily AtCoder # 49 in Python
Daily AtCoder # 27 in Python
Daily AtCoder # 1 in Python
Basic knowledge of Python
Daily AtCoder # 25 in Python
Daily AtCoder # 16 in Python
Daily AtCoder # 12 in Python
Daily AtCoder # 48 in Python
Daily AtCoder # 23 in Python
Daily AtCoder # 34 in Python
Daily AtCoder # 51 in Python
Daily AtCoder # 31 in Python
Daily AtCoder # 46 in Python
Daily AtCoder # 35 in Python
Daily AtCoder # 9 in Python
Daily AtCoder # 44 in Python
Daily AtCoder # 41 in Python
Atcoder ABC164 A-C in Python
Python Input Note in AtCoder
Atcoder ABC167 A-D in Python
Atcoder ABC165 A-D in Python
Atcoder ABC166 A-E in Python