python
| topics | 600-알고리즘 & 코딩테스트 |
| types | 레퍼런스 |
- output += f"{ans} "
- 파이썬 문자열은 불변이라 매번 새 문자열을 만들어요 → 누적하면 O(N^2) 가 됩니다.
- 첫 번째 코드는 리스트에 담아 join으로 출력 → O(N).
600-알고리즘 & 코딩테스트
graph_s.setdefault(a, set()).add(b)
파이썬 입력
swi_n=int(sys.stdin.readline().strip()) # 스위치 수
switches = list(map(int,sys.stdin.readline().strip().split()))
stu_n = int(sys.stdin.readline().strip())
all any
from collections import deque
import heapq
heap = []
heapq.heappush(heap, 50)
heapq.heapify(heap2)
result = heapq.heappop(heap)
import math
find 문자열 없어도 에러안나고 -1 뜸
index 없으면 에러남
회전
- 시계방향 90도
list(map(list, zip(*array [: : -1 ])))
- 반시계방향 90도
list(map(list, zip(*array)))[: :-1]
set
s1 = set([1, 2, 3])
l1 = list(s1)
# <span id="추가"></span>추가
s1.add(4)
# <span id="여러개-추가"></span>여러개 추가
s1.update([4, 5, 6])
# <span id="값-제거"></span>값 제거
s1.remove(2)
교집합 & ,차집합 - , 합집합 |
for문돌릴수는잇음
큐
from collections import deque
d = deque([1,2,3,4,5])
d.append(6)
d deque([1, 2, 3, 4, 5, 6])
d.appendleft(0)
d deque([0, 1, 2, 3, 4, 5, 6])
d.pop() # 6
d deque([0, 1, 2, 3, 4, 5])
d.popleft() # 0
d deque([1, 2, 3, 4, 5])
https://wikidocs.net/104977
회전도가능하다!
heapq
import heapq
heap = []
heapq.heappush(heap, 50)
heap2 = [50 ,10, 20]
heapq.heapify(heap2)
result = heapq.heappop(heap)
join
조인할때 대상이 str 인지확인해야함
안그러면조인안됨.
ans+=(' '.join(map(str,switches[start:end])))
타입체크
if isinstance(x, int):
dictionary
for key, value in {'a': 10, 'b': 20, 'c': 30, 'd': 40}.items():
print(key, value)
if "name" in car:
배열
파이썬에서 원본 배열(리스트)을 자르려면 슬라이싱 결과를 원본 리스트에 다시 할당하거나, 리스트의 일부를 삭제하는 방법을 사용할 수 있습니다. 슬라이싱은 기본적으로 새로운 리스트를 반환하므로, 이를 원본에 반영하려면 명시적으로 수정해야 합니다.
깊은 복사
import copy
list_A = ["ABC",["DEF","GHI"]]
list_B = copy.deepcopy(list_A)
이차원배열
list =[[0]*m for _ in range(n)]
원본 리스트를 직접 자르는 방법들:
- 슬라이싱 후 원본 리스트에 다시 할당하기
arr = [1, 2, 3, 4, 5]
# <span id="원본-리스트를-인덱스-1부터-3까지로-잘라서-다시-할당"></span>원본 리스트를 인덱스 1부터 3까지로 잘라서 다시 할당
arr = arr[1:3]
print(arr) # 출력: [2, 3]
del, 슬라이싱을 사용해 리스트의 일부분을 삭제하기
arr = [1, 2, 3, 4, 5]
# <span id="인덱스-1부터-3까지-삭제-인덱스-3은-포함되지-않음"></span>인덱스 1부터 3까지 삭제 (인덱스 3은 포함되지 않음)
del arr[1:3]
print(arr) # 출력: [1, 4, 5]
- 리스트 메서드
pop()사용
arr = [1, 2, 3, 4, 5]
# <span id="2번째-인덱스의-요소를-삭제"></span>2번째 인덱스의 요소를 삭제
arr.pop(2)
print(arr) # 출력: [1, 2, 4, 5]
remove()메서드 사용remove()는 리스트에서 특정 값을 삭제합니다. 값이 여러 개 있을 경우, 첫 번째로 발견된 값을 삭제합니다.
arr = [1, 2, 3, 4, 3, 5]
# <span id="값-3을-삭제-첫-번째로-등장한-3만-삭제됨"></span>값 3을 삭제 (첫 번째로 등장한 3만 삭제됨)
arr.remove(3)
print(arr) # 출력: [1, 2, 4, 3, 5]
- **리스트의 일부분을 잘라내고 원본을 수정하는 방법 추가
arr = [1, 2, 3, 4, 5]
# <span id="인덱스-1부터-3까지의-값을-8-9로-대체"></span>인덱스 1부터 3까지의 값을 8, 9로 대체
arr[1:3] = [8, 9]
print(arr) # 출력: [1, 8, 9, 4, 5]
# <span id="인덱스-2에-3-4를-삽입"></span>인덱스 2에 [3, 4]를 삽입
arr = [1, 2, 5, 6]
arr[2:2] = [3, 4]
print(arr) # 출력: [1, 2, 3, 4, 5, 6]
문자열
- 문자열 치환
text = "Hello world, Hello universe"
new_text = text.replace("Hello", "Hi")
print(new_text) # 출력: "Hi world, Hi universe"
- 앞뒤 패딩 채우기
Python에서 문자열.zfill(길이) 함수를 통해 왼쪽에 0을 채울 수 있습니다.
또한 문자열.rjust(길이, 채울문자), 문자열.ljust(길이, 채울문자) 함수를 통해 왼쪽, 오른쪽을 채울 수 있습니다.
정렬
student_tuples.sort(key=lambda x: x[2],reverse={bool})
sorted(arr, key=lambda x : (x[0], x[1])) // 여러개
//기본으로 람다에오는 기준에서 오름차순으로 비교함
// True 가 false보다 커서 True가 되는 조건을기준으로 추가할 수 있음
// 즉 false true 이순으로 온다는거임
arr.sort(key= lambda x:(int(x[0]), len(x)!=1, int(x[1])if len(x)>1 else 1001))
길이가 가변적이면 이렇게 할 수 있음
join
https://blockdmask.tistory.com/468
전개구문
https://zmade.tistory.com/50
구조분해할당
https://sozerodev.tistory.com/196
비트연산
https://un-gaemii.tistory.com/6
https://yiyj1030.tistory.com/267
count 로 특정문자열 개수세는게 가능
string ,array 다가능 https://dev-note-97.tistory.com/17
파이썬 none
https://gtidfocus.tistory.com/67
필터나 맵같은건 보통 앞에다가 함수를 씀
배열 위치 : https://sxbxn.tistory.com/35
a = None
result = a or "default"
count, index, find, join, strip
https://pycoding.tistory.com/entry/python-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%AC%B8%EC%9E%90%EC%97%B4-%EA%B8%B0%EB%B3%B8%ED%95%A8%EC%88%98-count-index-find-join-strip