0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

競技プログラミングでよく使われるPython関数その他もろもろ(ABC問題)

Last updated at Posted at 2021-03-28

チートシートみたいなものなので一度理解した人用です。

環境

  • Python 3.8.0

input () 系列

標準input()

n = input()
print(n)
# in:4 
# out:4

特定の文字区切りをinput()

a,b = map(int,input().split())    #input().split()でa,bに代入 それぞれをint型に変換
A =list(map(int,input().split()))
print(a)
print(A)
# in:4 9 
# out:4
# out:[4,9]

二次配列をinput()

Secondary = [list(map(int,input().split())) for i in range(3)]   #3は配列の長さ
print(Secondary)
# in: 
1 2
5 6
9 10
# out:
[[1, 2], [5, 6], [9, 10]]

文字列操作

文字列を一文字に分けList化

s="uncia002"
s_list = list(s[i:i+1] for i in range(len(s)))
print(s_list)
print("".join(s_list)) #Listから文字列にする

#['u', 'n', 'c', 'i', 'a', '0', '0', '2']
#uncia002

文字列を任意の数に分けList化

s="uncia002"
i=3
s_list = s[:i],s[i:]
print(list(s_list))
#['unc', 'ia002']

文字列の比較

defs="LOVINYOU"
def judge_str(index):return "V" in index
print(judge_str(s))
#True

リスト系 append(),extend(),insert()

追加系

A = [1,2,3,5,7]
A.append(11)    #末尾に追加
print(A)
A.extend(['','',''])   #リストの結合
print(A)
A.insert(0,0)  #任意の場所に追加(場所,値)
print(A)

#[1, 2, 3, 5, 7, 11]
#[1, 2, 3, 5, 7, 11, '松', '竹', '梅']
#[0, 1, 2, 3, 5, 7, 11, '松', '竹', '梅']

削除系

A = ['Python','JavaScript','Python','C']
a3 = A.pop(3)  #指定した位置の要素を削除し、値を取得
print(A)
print(a3)

A.remove('Python')  #指定した値の最初値を削除
print(A)

A=list(range(10))
A_fillted=[i for i in A if i % 2 == 0] #リストから条件式に基づいて削除する
print(A_fillted)

#['Python', 'JavaScript', 'Python']
#C
#['JavaScript', 'Python']
#[0, 2, 4, 6, 8]

mathライブラリ

平方根

import math
print(math.sqrt(5))

#2.23606797749979

小数点切り捨て、切り上げ

import math
print(math.floor(10.123)) #切り捨て
print(math.ceil(10.123)) #切り上げ
# 10
# 11

int()は四捨五入

その他

min()max()

a,b=5,6
print(min(a,b))
print(max(a,b))

#5
#6

絶対値

print(abs(-1.22))
#1.22

約数を出力

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort()
    return divisors

print(make_divisors(100))

#[1, 2, 4, 5, 10, 20, 25, 50, 100]

素数判定(近似) 

import math
def is_prime(n):
    if n == 1: return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False

    return True

print(is_prime(13))  

引用

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?