관리 메뉴

진취적 삶

코테를 위한 파이썬 문법 본문

알고리즘/이것이 취업을 위한 코딩 테스트이 with 파이썬

코테를 위한 파이썬 문법

hp0724 2023. 7. 10. 18:44

sort

리스트의 원소로 리스트나 튜플이 존재할때 특정한 기준에 따라서 정렬 수행

result =sorted([('홍길동',24),('이순신',75),'('아무개',50)] ,key=lambda x:x[1].reverse =True)

itertools

파이썬에서 반복되는 데이터를 처리하는 기능

순열 permutations, 조합 combinations 기능을 가지고있다.

from itertools import permutations 
data= ['a','b','c'] 
result = list(permutations(data,3)
from itertools import combinations 

data = ['a','b','c']
result = list(combinations(data,2))

heapq

다익스트라 최단 경로 알고리즘을 포함해 우선순위 큐 기능을 이용하고자 할때 사용

파이썬은 최소힙으로 구성되어 있어 원소를 힙에 전부 넣어다가 빼는것만으로

시간복잡도 O(NlogN)에 오름차순 정렬

import heapq 
def heapsort(iterable):
    h= []
    result = []

    for value in iterable:
        heapq.heappush(h,value)
    
    for i in range(len(h)):
        result.append(heapq.heappop(h))
    return result

result =heapsort([1,3,5,7,9,2,4,6,8])
print(result)

파이썬은 최소 힙으로 구성하니깐 내림차순으로 정렬하려면 원소의 부호를 임시로 변경

import heapq 
def heapsort(iterable):
    h= []
    result = []

    for value in iterable:
        heapq.heappush(h,-value)
    
    for i in range(len(h)):
        result.append(-heapq.heappop(h))
    return result

result =heapsort([1,3,5,7,9,2,4,6,8])
print(result)

bisect

시간 복잡도 O(logN)

  • bisect_left(a,x) : 정렬된 순서를 유지하면서 리스트 a에 데이터를 x를 삽입할 가장 왼쪽인덱스를 찾는 메서드
  • bisect_right(a,x): 정렬된 순서를 유지하도록 리스트 a에 데이터 x를 삽입할 가장 오른쪽 인덱스를 찾는 메서드
from bisect import bisect_left, bisect_right

a =[1,2,4,4,8]
x=4
print(bisect_left(a,x)) # 2
print(bisect_right(a,x))# 4

collections

deque와 Counter

from collections import deque

data = deque([2,3,4])
data.appendleft(1)
data.append(5)

print(data) #deque([1, 2, 3, 4, 5])
from collections import  Counter

counter = Counter(['red','blue','green','red','blue','green','red','blue','green'])


print(counter['blue']) #3
print(dict(counter))# {'red': 3, 'blue': 3, 'green': 3}

'알고리즘 > 이것이 취업을 위한 코딩 테스트이 with 파이썬' 카테고리의 다른 글

최단 경로 문제  (0) 2023.07.10
그래프 이론 문제  (0) 2023.07.10
기타 알고리즘  (0) 2023.07.10
구현 문제  (0) 2023.07.10
DFS/BFS 문제  (0) 2023.07.10