アルゴリズム構文クリーンアップ📌


コード化時に使用する文法の母音をテストします!💕
heap-臀部
import heapq # 기본은 min-heap, max-heap 사용시 -값 넣기

lst = [1, 2, 3]
heapq.heapify(lst)
# 빈 배열은 push시 자동으로 힙으로 됨
empty = []
💡 挿入/削除/ブラウズ
heapq.heappop(my_list)
heapq.heappush(my_list, -1)
my_list[0]
queue-Q✔✔
from collections import deque
que = deque([1, 2, 3])
💡 エレメントの中間を挿入
que.insert(i, num)
💡 挿入/削除/ブラウズ
que.append(item)
que.popleft()
que[0]
counter ✔️
import collections
my_list = ["a", "a", "b", "b", "c"]
collections.Counter(my_list)

# Counter({'a': 2, 'b': 2, 'c': 1})
itertools ✔️
import itertools
from itertools import permutations
from itertools import combinations
from itertools import product
from itertools import chain
💡 整列
permutations(range(1, 10), 3)
permutations(lst)
💡 を選択します.
combinations('ABC', 2)
💡 製品-繰り返しシーケンス
product(range(1,n1+1), range(1,n2+1), range(1,n3+1))

or_not = [(0, 500), (0, 1500)]
list(product(*or_not))

#[(0,0), (0,1500), (500,0), (500,1500)]
💡 chain-platting(マイナー・スキーマ->プライマリ・スキーマ)
itertools.chain(*board)
chain(*board)
dictionary-#
💡 get
my_dict['total']
my_dict.get('total', 0)
💡 削除-pop:鍵がない場合はdefaultを返します.
my_dict.pop('홍길동', 180)
💡 探索する
dict.items()
dict.keys()
dict.values()
💡 グラフィック設定:getの使用
nodes = {}
for v1, v2 in edge:
    nodes[v1] = nodes.get(v1, []) + [v2]
    nodes[v2] = nodes.get(v2, []) + [v1]
💡 dist:getを使用してグラフィックを設定する
nodes = {}
for v1, v2, d in road:
    nodes[v1] = nodes.get(v1, []) + [(v2, d)]
    nodes[v2] = nodes.get(v2, []) + [(v1, d)]
💡 図の距離をリセット
dist = { i:float('inf') if i != 1 else 0 for i in range(1, N+1) }
defaultdict ✔️
from collections import defaultdict

dict1 = defaultdict(set)
dict2 = defaultdict(list)
dict3 = defaultdict(int) -> 0으로 셋팅
💡 グラフィック設定:defaultdictの使用
from collections import defaultdict
nodes = defaultdict(list)
for v1, v2 in edge:
    nodes[v1].append(v2)
    nodes[v2].append(v1)
set-3✔✔
💡 挿入/削除
my_set.add(3)
my_set.remove(3)
💡 include
if 3 in my_set:
	print('3 있음')
if 3 not in my_set:
	print('3 없음')
💡 交差
set1 | set2
set1.update(set2)

set1 - set2

set1 & set2
bisect ✔️
from bisect import bisect_left, bisect_right
💡 最小値の左側(最小値を含むインデックス)
bisect_left(lst, start)
💡 右端の最大値(最大値を含むインデックス)
bisect_right(lst, end)
💡 count_by_lange
def count_by_lange(lst, start, end):
    return bisect_right(lst, end) - bisect_left(lst, start)
DELTA-方向✔
DELTAS = [(0, 1), (0, -1), (-1, 0), (1, 0)] # 오른쪽 왼쪽 위 아래
DELTAS = [(-1, 0, UP), (1, 0, DOWN), (0, 1, RIGHT), (0, -1, LEFT)]
DELTAS = {'U':(0, 1), 'D':(0, -1), 'L':(-1, 0), 'R':(1, 0)}

DELTAS = {'U': (-1, -1), 'D': (1, 0), 'R': (0, 1)}
NEXT = {'U': 'D', 'D': 'R', 'R': 'U'}
Visibable-ナビゲーション範囲を確認✔
def visitable(y, x, m, n):
    return 0 <= y < m and 0 <= x < n
素数✔
N, primes = end_num, set()
prime_check = [False, False] + [True]*(N-1)

for i in range(2, N+1):
    if prime_check[i]:
        primes.add(i)
        prime_check[i*2::i] = [False] * len(prime_check[i*2::i])
最小公倍数/最大公因数✔
💡 最大公約数
from fractions import gcd
gcd(6,8) # 2
💡 最小公倍数
def lcm(a,b):
    return  a * b // gcd(a, b)
倍表示✔
[(number//i, i) for i in range(1, int(number**.5)+1) if number % i == 0]
# number = 24 -> 곱해서 24가되는 경우
[(24, 1), (12, 2), (8, 3), (6, 4)]
✔✔
💡 最小値
def impossible(n, middle, times):
    return sum([middle // x for x in times]) < n

def solution(n, times):
    left, right = 1, max(times)*n
    while left < right:
        middle = (left + right) // 2
        if impossible(n, middle, times): 
            left = middle + 1
        else: 
            right = middle
    return left
💡 最大値
def is_poss(middle, budgets, M):
    return M >= sum([min(middle, budget) for budget in budgets])

def solution(budgets, M):
    left, right = 1, max(budgets)
    while left < right:
        middle = (left + right + 1) // 2 
        if is_poss(middle, budgets, M):
            left = middle
        else:
            right = middle - 1
    return right
sort ✔️
💡 sort
lst.sort()
dist.sort(reverse=True)
lst.sort(key= lambda x : (x*4)[:4], reverse=True)
💡 sorted
sorted(lst)
sorted(lst, reverse=True)
sorted(answer, key = lambda x : (x[0], -x[1], x[2]))
count ✔️
💡 要素の数
lst.count(0)
[*row, *col, *diag].count(n)
💡 filter count
filter = [item for item in items if 조건식 ]
len(filter)
二次アレイ✔
💡 m*nマトリクスの初期化
board = [[0] * n for i in range(m)]
💡 反転行(n*m)
reversed = list(map(list,zip(*board)))
💡 90度回転
def rotate90(arr):
    return list(zip(*arr[::-1]))
string ✔️
💡 置換文字
query.replace('?','a')
💡 相対
s.split("},{")
💡 join
number = int(''.join(x))
💡 文字列数で分割
splited = [s[i:i+size] for i in range(0, LENGTH, size)]
# size = 3 : aabbaccc -> ['aab', 'bac', 'cc']
正規式
import re
💡 検索
re.search("^"+pre+".+",number)
re.findall(query, word)
lst = re.findall('\d+',s)
# ['2', '2', '1', '3', '4']
re.compile("(\D)")
円形リニア✔
weak_point = weak + [w+n for w in weak]
math ✔️
import math
💡 ceil
math.ceil(num / div)
💡 factorial
math.factorial(3)