Python 코딩테스트

2024. 10. 4. 20:36백준 & 프로그래머스

문자열 뒤집기

print(string[::-1])

중복제거

print(list(set(tmp)))

zip 함수

for n1, n2 in zip(tm1, tm2):
    print(n1, n2)

dict 정렬

dic = {'a' : 3, 'b' : 1, 'c' : 5}
sorted(dic) # key로 sort
sorted(dic.item(), key = lambda x: x[1])
sorted(dic.item(), key = lambda x: (x[1], x[0]))

2차원배열에서 열 추출

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = list(zip(*a))[0]

깊은 복사

import copy

copied = copy.deepcopy(ori)

실수 표현 정확도 한계

a = 0.3 + 0.5
if a == 0.8:
    print(True)

# Tru가 나오지 않음 차라리
a = round(0.3 + 0.5, 1)

str 내장함수

lower
upeer
find # 여러개인 경우 앞쪽
count

list 내장함수

a.sort(resverse = True)
sorted(a, reverse = True)

set

s = {a, b}
s. update([c, d])

list를 문자열로 join

arr = ['1', '2', '3']
print(int(''.join(arr))) # 123

itertools

  • permutations
  • combination
  • product
  • combination_with_replacement
from itertools import permutations, combinations, product, combinations_with_replacement

data_list = ['A', 'B', 'C']

result = list(permutations(data_list, 3))
result = list(combinations(data_list, 2))
result = list(product(data_list, repeat=2))
result = list(combinations_with_replacement(data_list, 2))

PQ = heap

heap을 역순으로 하고 싶다면, 변수에 -를 붙이면 된다.

bisect

bisect_left(iterable, value) : 정렬된 순서를 유지하면서 iterable에 value를 삽입할 가장 왼쪽 인덱스 구하기
bisect_right(iterable, value) : 정렬된 순서를 유지하면서 iterable에 value를 삽입할 가장 오른쪽 인덱스 구하기

import bisect

lst = [1,2,3,4,5,6]

# 숫자가 존재한다면, bisect_left :그 숫자의 가장왼쪽 index, bisect_right :  그 숫자의 가장 오른쪽 + 1
# 숫자가 존재하지 않는다면, 해당 숫자가 들어갈 index 반환한다.

# https://ssooyn.tistory.com/11

math

import math

print(math.sqrt(5)) # 제곱근
print(math.factorial(5)) # 팩토리얼
print(math.gcd(35,14)) # 최대공약수
print(math.pi) # pi
print(math.e) # 자연상수 e

# 내림
print(math.floor(3.14))  # 결과 : 3
print(math.floor(-3.14)) # 결과 : -4

# 올림
print(math.ceil(3.14))  # 결과 : 4
print(math.ceil(-3.14)) # 결과 : -3

# 반올림 -> 파이썬 내장함수 round()를 사용한다.
print(round(3.1415))      # 결과 : 3
print(round(3.1415, 2))   # 결과 : 3.14
print(round(31.415, -1))  # 결과 : 30.0