Python 코테 모음집

파닥몬·2022년 10월 10일
0
post-thumbnail

주절주절.

원래 코테 볼 때 c++을 이용한다. 알고리즘 동아리에서 계속 c++로 해와서 제일 편하기 때문이다. 주변엔 python으로 갈아탄 사람이 많았지만, 난 계속 c++을 이용했다.

하지만... 최근 한 회사에 지원해서 코테를 보게 되었고, c++은 코테 언어에 포함되지 않은 것을 봤다. 지원되는 언어 중 python이 가장 할만 하다고 생각했다.

그래서 써보는 글...!

⚙️ 자료구조 및 라이브러리

1️⃣ Priority Queue

다익스트라 알고리즘 구현에 있어서 절.대 빠지면 안 되는 자료구조.
다행히 별도의 설치 없이 사용할 수 있는 라이브러리가 존재한다.

from queue import PriorityQueue

def dijkstra(start):
	pq=PriorityQueue()
    pq.put((0, start))
    dist[start]=0
    while pq:
    	now_dist, now=pq.get()
        now_dist = now_dist*(-1)
        for next_node, next_w in v[now]:
        	if dist[next_node]>next_w+now_dist:
            	dist[next_node]=next_w+now_dist
  • 추가: put()
  • 삭제: get() (만약 tuple의 index을 얻고 싶다면 get[1])(pop과 동시에 top이 나옴)

1️⃣-1️⃣ Queue

사실 잘 안 쓰긴 하지만... 그래도 알아두면 좋으니께!

queue=[]
queue.append(1)
queue.append(2)
// queue[0]==top
queue.pop(0)
// queue=[2]
  • 추가: append()
  • 삭제: pop(0) (queue의 특징은 맨 앞 원소를 삭제하는 것이다.)

2️⃣ Stack

은근히 자주 쓰는 자료구조.

stack=[]
stack.append(1)
stack.append(2)
// stack[-1]==top
stack.pop()
// stack=[1]
  • 추가: append()
  • 삭제: pop()

3️⃣ Map

나의 최애 자료구조. 얘 없으면 안 된다ㅠ
python의 dictionary라는 자료구조와 매우 유사하다.

dict={}
// value가 primitive type
dict['A']=65
// value가 list
dict['A']=[65]
dict['A'].append(66)

del dict['A']
  • 선언: dict={} (중괄호가 dictionary라는 의미다.)
  • 추가: dict[key]=value
  • 삭제: del dict[key]

c++과 다르게 편한 점은 for문 돌릴 때다.

// c++
for(auto it=m.begin(); it!=m.end(); it++)
// python
for key, val in dict

4️⃣ Algorithm

쓸만한 것이 꽤 많은 라이브러리. 얘도 꼭 필요하다. 특히 정렬...

4️⃣-1️⃣ sort

arr=[1,2,5,4]
// 오름차순
arr=sorted(arr) => [1,2,4,5]
// 내림차순
arr=sorted(arr, reverse=True) => [5,4,2,1]

struct_arr=[('PDM', 20, 'W'), ('HO', 18, 'M')]
// 한 원소를 기준으로 정렬 -> key=lambda ele: ele[1]
// 만약 class 형태라면 -> key=lambda ele: ele.age
struct_arr=sorted(struct_arr, key=lambda struct: struct[1])
  • sorted를 사용하면 꼭! 다시 배열에 넣어줘야 한다.
    만약 쓰기 이를 쓰기싫다면, arr.sort() 라고 쓸 수 있다.
    reverse, key 쓰는 건 동일하지만, 얘는 list type일 때만 적용된다.

4️⃣-2️⃣ next_permutation

import itertools as iter
arr=['A','B','C']
// 순열
// [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
nPr=list(iter.permutations(arr))
// [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
nP2=list(iter.permutations(arr, 2))

// 조합
// [('A', 'B'), ('A', 'C'), ('B', 'C')]
nCr=list(iter.combinations(arr, 2))
  • list로 안 감싸면 <itertools.permutations object at 0x7f13414f5b90> 이렇게 출력된다. list로 감싸주기.
  • permutations, combinations다. s 붙이는 거 잊지말자!
  • 순열과 조합의 차이는 출력을 보면 알겠지만, (1,2)와 (2,1)을 다르게 보면 순열! 같게 보면 조합!

5️⃣ 구조체

한 객체에 여러 정보를 저장할 때 필요한 구조체.
그냥 tuple을 사용하면 된다. 혹은 class를 이용한다.

// (이름, 나이, 성별)을 넣는다고 가정
// tuple
tuple_list=[]
t=('PDM', 20, 'W')

// class
class Student:
  def __init__(self, name, grade, age):
    self.name = name
    self.grade = grade
    self.age = age
  def __repr__(self):
    return repr((self.name, self.grade, self.age))

student=[Student('PDM',1,12), Student('HO',1,15)]
print(sorted(student, key=lambda stu: -stu.age))
// [('HO', 1, 15), ('PDM', 1, 12)]

__repr__ : 객체를 문자열로 반환하는 함수
class 내에 안 적어주면 print(student) 했을 때 <__main__.Student object at 0x7ff8c2046090> 이런 값이 들어간 list가 나온다. 그러니 꼭! 써주기!

🔥 자주 쓰는 Skill

1️⃣ 중복 제거

// set 이용
arr=[1,2,3,3,4,5]
arr=list(set(arr)) => [1, 2, 3, 4, 5]

2️⃣ for문

arr=[1,2,3,3,4,5]
// index 기준
for idx in range(len(arr)):
	print(idx) => [0,1,2,3,4,5]
    
// item 기준
for num in arr:
	print(num) => [1,2,3,3,4,5]

3️⃣ 자르기

str="The secret makes the woman, woman."
// ➡️ split -> split 함수 이용
// 1. 공백 기준
sp=str.split() => ['The', 'secret', 'makes', 'the', 'woman,', 'woman.']
// 2. 특정 단일 문자 기준
sp=str.split(',') => ['The secret makes the woman', ' woman.']
// 3. 정규식 기준(복수 문자 기준)
import re
sp=re.split('[,.]', str) => ['The secret makes the woman', ' woman', '']

// ➡️ substr -> slicing 이용
// 여담으로 일반 list도 slicing 가능하다.
sp=str[:5] => 'The s'
profile
파닥파닥

0개의 댓글