728x90
- 컴파일 타임에 변수 이름 잘못 넣어도 추론 안됨
elif last_four_words == "infl":
print("Orthopedics")
elif last_for_words == "skin": << 오타인데 런타임까지 검출 안됨
- 주석
# 123asdasd
- 연산
# 반올림
round(0.7) # 1
round(123.456, 2) # 123.46
# 나누기
2 / 3 # 0.6666666666666666
# 나머지
2 % 3 # 2
# 몫
2 // 3 # 0
# 제곱
2 ** 3 # 8
# 삼항 연산
True if x % 2 == 0 else False
# or, 하나라도 True면 True
any([True, False, False]) # True
# and, 모두 True여야 True
all([False, False, False]) # False
- 함수 정의
def solution(arr):
answer = []
return answer
- 배열
# 원소를 넣어 초기화
a = [1, 2, 3, 4, 5] # [1, 2, 3, 4, 5]
# repeat
a = [0] * 5 # [0, 0, 0, 0, 0]
# init
a = list() # []
# 조건 init
a = [i for i in range(20) if i % 2 == 1] # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
a = [i*i for i in range(1,10)] # [1, 4, 9, 16, 25, 36, 49, 64, 81]
## 다차원 배열
n = 3
m = 4
a = [[0]*m for _ in range(n)] # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# 배열 순회
for i in range(0, 5): # 0, 1, 2, 3, 4
print(i)
# 크래시 없는 마지막 원소 검사
a = []
for i in s:
if a[-1:] == [i]: continue # a[-1:] -> [마지막 원소] == [i]
a.append(i) # i 원소 추가
# 빈배열 검사
return not a
# 인덱스 enumerate
[(i, e) for i, e in enumerate([6, 5, 4, 3, 2, 1])] # [(0, 6), (1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]
list(enumerate([6, 5, 4, 3, 2, 1]) # [(0, 6), (1, 5), (2, 4), (3, 3), (4, 2), (5, 1)
# 인덱스 검사
[1, 2, 3, 4].find(1) # 0, 없으면 -1 반환, 문자열만 가능
[1, 2, 3, 4].index(1) # 0, 없으면 ValueError, iteratable 가능
# prefix
s.startswith(keyword, start, end) # s가 keyword로 시작하는지 검사
# suffix
s.endswith(keyword, start, end) # s가 keyword로 끝나는지 검사
- 딕셔너리
# 초기화
dict = {}
# 기본 값 설정
for i in arr:
dict.setdefault(i, 0)
dict[i] += 1
# 키만 순회
for key in dict:
# 키, 값 순회
for key, value in dict.items():
for key in dict.keys():
for value in dict.values():
###
from collections import defaultdict
a = defaultdict(int) # 0
b = defaultdict(list) # []
c = defaultdict(lambda: 1 ) # 1
d = defaultdict(lambda: [1, []] ) # [1, []]
# 제거
del sample_dict['영어']
sample_dict.pop('수학', None)
- 카운터
from collections import Counter
Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
# Counter({'blue': 3, 'red': 2, 'green': 1})
Counter("hello world")
# Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# counter["o"] -> 2
# counter["l"] -> 3
# o in counter -> True
# o not in counter -> False
Counter('hello world').most_common(2)
# [('l', 3), ('o', 2)]
counter1 = Counter(["A", "A", "B"])
counter2 = Counter(["A", "B", "B"])
counter1 + counter2
# Counter({'A': 3, 'B': 3})
counter1 - counter2
# Counter({'A': 1}) -> 0 혹은 음수면 key 제거
- and, or 연산자
i == j or i == k
i == j and i == k
- map
def square(x):
return x**2
# 함수 map
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers) # [1, 4, 9, 16, 25]
# 람다 map
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda n: n ** 2, numbers)
def add(x, y):
return x + y
# 배열 2개 map
numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30, 40, 50]
added_numbers = map(add, numbers1, numbers2) # [11, 22, 33, 44, 55]
# int 초기화 map
a = list(map(int, 1.2, 2.5, 3.7, 4.6])) # 1 2 3 4
- 입력 분할
x = input().split() # "10 20"
m = map(int, x) # [10, 20]
a, b = m # 10, 20
- reduce
from functools import reduce
def SumFunction(x, y): return x + y
print(reduce(SumFunction, list(range(1, 21)))) # 210
# 기본 값
print(reduce(SumFunction, list(range(1, 21), 10))) # 220
- 정렬
# 기본값 (오름차순)
a.sort()
# 오름차순
b.sort(reverse=False)
# 내림차순
c.sort(reverse=True)
# 문자열의 길이 순 정렬
lst.sort(key=len)
# 절대값 기준 정렬
lst.sort(key=abs)
# sorted
new_list = sorted(lst3, reverse=True)
# 튜플에서 2번 째 원소를 기준
lst1 = [('apple', 3), ('banana', 1), ('kiwi', 2), ('orange', 4)]
lst1.sort(key=lambda x: x[1])
# 튜플에서 2번 째 원소를 기준으로 내림차순, 3번 쨰 원소를 기준으로 오름차순
lst3 = [['apple', 1, 300], ['banana', 2, 150], ['kiwi', 2, 400], ['orange', 1, 1000]]
lst3.sort(key=lambda x: (-x[1], x[2]))
- 문자열
# 모든 문자를 소문자, 대문자로 변환
s.upper()
s.lower()
# 모든 문자가 소문자, 대문자인지 검사
s.isupper()
s.islower()
# 모든 앞글자 대문자로
s.title()
# 조건 카운트
s.count("0")
# 문자열 변환
s.replace("0", "")
# 2진 변환
s = bin(len(s))[2:] # 0b11 -> 11
# 알파벳 생성
import string
# 소문자 리스트
lower = [i for i in string.ascii_lowercase]
# 대문자 리스트
upper = [i for i in string.ascii_uppercase]
# 대문자+소문자 전체 리스트
lowup = [i for i in string.ascii_letters]
# 문자열 기준 조인
"."join(["a", "b", "c", "d"]) # a.b.c.d
# 왼쪽 문자열 스트립
" apple".lstrip() # 왼쪽 공백 제거 -> apple
" apple".lstrip("ap") # "a", "p"의 모든 조합 제거 -> le
# 오른쪽 문자열 스트립
"apple ".rstrip() # apple
"apple".rstrip("lep") # "l", "e", "p" 모든 조합 제거 -> a
# 문자열 스트립
" apple ".strip() # apple
"apple".strip("ae") # "a", "e"의 모든 조합 제거 -> ppl
- 수학
import math
# 최대공약수
math.gcd(3) # 3
math.gcd(3, 6) # 3
math.gcd(11, 22, 66) # 11
# 최소공배수 python 3.9 이상
math.lcm(2) # 2
math.lcm(2, 4) # 4
math.lcm(11, 22, 66) # 66
# 최소공배수 구현
def lcm(a, b): return a * b / math.gcd(a, b)
# 순열
from itertools import permutations
perm = list(permutations([1, 2, 3, 4], 2)) # [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
# 조합
from itertools import combinations
combi = list(combinations([1, 2, 3, 4], 2)) # [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
# 중복 순열
from itertools import product
prod = list(product([1, 2, 3, 4], [1, 2, 3, 4])) # [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
list(product([1, 2], ['A', 'B'])) # [(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
list(product([0, 1], repeat = 3)) # [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
# 중복 조합
from itertools import combinations_with_replacement
combi_with_repl = list(combinations_with_replacement([1, 2, 3, 4], 2)) # [(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]
# 올림
math.ceil(1.0) # 1
math.ceil(1.1) # 2
math.ceil(2.1) # 3
math.ceil(-3.2) # -3
# 내림
math.floor(1.0) # 1
math.floor(1.1) # 1
math.floor(2.1) # 2
math.floor(-3.2) # -4
- set
# 초기화
s = set()
# 요소 추가
s.add(x)
# 특정 요소 제거, 요소 없으면 에러
s.remove(x)
# 특정 요소 제거, 요소 없으면 패스
s.discard(x)
# 특졍 요소 제거 및 반환, 없으면 에러
s.pop()
# 모든 요소 제거
s.clear()
# 길이
len(s)
# 복사
copy(set)
# 합집합
s1 | s2 # set.union(s1, s2)
# 차집합
s1 - s2 # set.difference(s1, s2)
# 교집합
s1 & s2 # set.intersection(s1, s2)
# 대차집합
s1 ^ s2 # set.symmetric_difference(s1, s2)
# 연산식
s1 |= s2 # s1.update(s2)
s1 \&= s2 # s1.intersection_update(s2)
s1 -= s2 # s1.difference_update(s2)
s1 \^= s2 # s1.symmetric_difference_update(s2)
- 큐
import queue
# queue 라이브러리는 top 못 봄 collections deque를 queue로 써야함
q = queue.Queue()
pq = queue.PriorityQueue()
lifoQ = queue.LifoQueue()
# push
q.put()
# 사이즈
q.qsize()
# pop
q.get()
# empty
q.empty()
from collections import deque
q = deque()
# 추가
q.append(1)
# 제거
q.pop()
# subscript 가능
q[0]
import heapq
hq = []
# 삽입
heapq.heappush(hq, 4) # 힙 큐 hq에 4 삽입
# pop
heapq.heappop(hq) #
# 접근
hq[0]
# 배열 -> 힙 큐 변환
heapq.heapify([5, 2, 6, 4, 1, 3]) # [1, 2, 3, 4, 5, 6]
- 에러
# ValueError: invalid literal for int() with base 10:
int(s) # s에 .이 있을 때, ex. 136.5 -> float로 변환 후
728x90
'Algorithm' 카테고리의 다른 글
Swift 알고리즘 관련 문법 (0) | 2025.03.30 |
---|---|
SwiftUI: [1차] 뉴스 클러스터링 (0) | 2024.04.04 |
SwiftUI: [1차] 캐시 (0) | 2024.04.03 |
SwiftUI: 의상 (0) | 2024.04.02 |
SwiftUI: H-Index (0) | 2024.04.02 |