[Python] 코딩 테스트 대비 외워두면 유용한 코드

전현준·2024년 7월 16일
0

Algorithm

목록 보기
1/13

객체의 메소드 알아내기

dir 내장 함수를 사용하면, 각 객체의 메소드를 알아낼 수 있다.

a = list()
print(dir(a))
['__add__', '__class__', '__class_getitem__', '__contains__',
'__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', 
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', 
'__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', 
'__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

이렇게 갑자기 메소드를 까먹었을 때, 유용하다.


입력 시간 줄이기


  • 백준에서 입력 받을 때, input은 시간 초과가 날 수도 있다.
  • input() 대신 sys.stdin.readline()으로 대체하는 것이 좋다
import sys
L, C = map(int, sys.stdin.readline().split())

Counter


  • String의 특정 문자의 갯수가 몇개인지 알기 좋음
from collections import Counter

counter = Counter("hello")
counter["l"] >> 2
counter["o"] >> 1

조합, 순열, 중복 순열


조합

from itertools import combinations
temp_list = list(combinations(["a","b","c"], 2))

순열

from itertools import permutations
temp_list = list(permutations(["a","b","c"], 2))

중복 순열

from itertools import product
temp_list = list(product(["a","b","c"], ["a","b","c"]))
temp_list = list(product(["a","b","c"], repeat=2))

리스트


리스트 한번에 출력

A = [1,2,3,4,5]
print(A) # [1,2,3,4,5]
print(*A) # 1 2 3 4 5

문자열


문자열 뒤집기

T = "hi"
r = reversed(T)
T = ''.join(r).strip()

문자열 대문자 / 소문자

answer = "hi"
answer.upper() # HI
answer.lower() # hi

문자열 및 공백 제거

앞 뒤의 공백이나 문자를 제거

answer =   "     hi   "
answer.strip()   #hi

answer = 'aaaaaabb'
answer.rstrip('a') #bb

정렬

key로 정렬

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

list.sort(key = lambda x : x[0]) # 앞 element 기준으로 정렬
profile
백엔드 개발자 전현준입니다.

0개의 댓글