<h1><center> Python 코테 문법 정리 </center></h1> ###### tags: `💻 TIL` ###### date: `2024-03-17T15:12:33.284Z` > [color=#724cd1][name=데릭] ## 파이썬 수행 시간 측정 ```python import time start_time = time.time() # 측정 시간 # 프로그램 소스코드 end_time = time.time() # 측정 종료 print(end_time - start_time) # 수행 시간 출력 ``` **자료형 연산** - 나누기: / - 나머지: - 몫: // - 거듭 제곱: ** **집합 자료형의 연산** - 합집합: | - 교집합: & - 차집합: - ```python= a = set([1,2,3,4,5]) b = set([3,4,5,6,7]) print(a|b) print(a&b) print(a-b) # {1, 2, 3, 4, 5, 6, 7} # {3, 4, 5} # {1, 2} data = set([1,2,3]) print(data) # 새로운 원소 추가 data.add(4) # 새로운 원소 여러 개 추가 data.update([5,6]) # 특정한 값을 갖는 원소 삭제 data.remove(3) print(data) 출처: https://seongbindb.tistory.com/54 [SeongbinDB:티스토리] ``` ### List **리스트 초기화** ```python arr = [0] * n # n = 3 print(arr) # [0, 0, 0] ``` **인덱싱 슬라이싱** ```python arr = [1, 2, 3] # arr[a:b] print(arr[0:2]) # [1, 2] print(arr[-1]) # 3 print(arr[2:]) # 3 ``` **List Comprehension** ```python array = [i for in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] array = [i for i in range(20) if i % 2 == 1 # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] n = 3 m = 2 arr = [[0] * m for _ in range(n)] # 2차원 배열 print(arr) # [[0, 0], [0, 0], [0, 0]] ``` **리스트 관련 기타 메서드** - arr.append() : $O(1)$의 시간복잡도를 가지고 리스트 마지막에 원소를 넣음 - arr.sort() : $O(NlogN)$의 시간복잡도를 가지고 기본 정렬 기능으로 오름차순 정렬 - arr.sort(reverse=True): 내림차순으로 정렬 - arr.reverse(): 리스트 원소를 뒤집는다. $O(N)$ - arr.insert(삽입위치, value): $O(N)$ - arr.count(value): $O(N)$로 리스트에서 특정 값을 가지는 데이터의 개수를 셀 때 사용. - arr.remove(value): 리스트에서 특정 값을 가지는 원소를 제거, 여러 개면 하나만 제거함. $O(N)$ - pop(x): x번째 인덱스의 요소를 리스트에서 삭제한다. **리스트에서 특정 값을 가지는 원소를 모두 제거하기** ```python a = [1,2,3,4,5,5,5] remove_set = {3, 5} result = [i for i in a if i not in remove_set] print(result) # [1, 2, 4] ``` **람다 표현식** ```python list1 = [1,2,3,4,5] list2 = [6,7,8,9,10] result = map(lambda a,b : a+b, list1,list2) print(list(result)) # [7, 9, 11, 13, 15] ``` ```python def add(a, b): return a + b print(add(3,7)) # 람다 표현식으로 구현한 add() 메서드 print( (lambda a, b: a + b)(3,7) ) ``` **정렬** ```python= fruits = { 'apple': 2, 'banana' : 1, 'pear' : 2, 'melon' : 0, 'plum' : 1} #key 기준 정렬 res = sorted(fruits) print(res) # ['apple', 'banana', 'melon', 'pear', 'plum'] #value 기준 정렬 res = sorted(fruits, key=lambda k : fruits[k]) print(res) # ['melon', 'banana', 'plum', 'apple', 'pear'] ``` ### Map ```python members = {'name': '김태현', 'age': 33, 'phone': '010-0000-0000'} print(members) # {'name': '김태현', 'age': 33, 'phone': '010-0000-0000'} ``` ```python key_list = data.keys() value_list = data.values() ``` ```python phones = {'갤럭시 노트8': 2017, '갤럭시 S9': 2018, '갤럭시 노트10': 2019, '갤럭시 S20': 2020} print(phones) for phone in phones : print('%s => %s' % (phone, phones[phone])) print(len(phones)) # 갤럭시 노트8 => 2017 # 갤럭시 S9 => 2018 # 갤럭시 노트10 => 2019 # 갤럭시 S20 => 2020 # 4 ``` ### 순열과 조합 순열: 서로 다른 n개에서 서로 다른 r개를 선택하여 일렬로 나타내기이다. $$_{n}P_{r}$$ 조합: 서로 다른 n개에서 순서에 상관 없이 서로 다른 r개를 선택한다. $$_{n}C_{r}$$ **순열** ```python from itertools import permutations arr = [1, 2, 3] perms = permutations(arr, 3) for perm in perms: print(perm) # (1, 2, 3) # (1, 3, 2) # (2, 1, 3) # (2, 3, 1) # (3, 1, 2) # (3, 2, 1) ``` **중복 순열** ```python from itertools import product arr = [1, 2, 3] duplicated_perms = product(arr, repeat=2) # 2개를 뽑는 모든 순열 구하기(중복을 허용함) for perm in duplicated_perms: print(perm) # (1, 1) # (1, 2) # (1, 3) # (2, 1) # (2, 2) # (2, 3) # (3, 1) # (3, 2) # (3, 3) ``` **조합** ```python from itertools import combinations arr = [1, 2, 3] combs = combinations(arr, 2) for comb in combs: print(comb) # (1, 2) # (1, 3) # (2, 3) ``` **중복 조합** ```python from itertools import combinations_with_replacement arr = [1, 2, 3] combs = combinations_with_replacement(arr, 2) for comb in combs: print(comb) # (1, 1) # (1, 2) # (1, 3) # (2, 2) # (2, 3) # (3, 3) ``` **최대 공약수와 최소 공배수** - 최대 공약수는 math의 gcd() ```python import math a = 24 b = 36 # 최대 공약수 계산 gcd = math.gcd(a, b) print(f"The Greatest Common Divisor (GCD) of {a} and {b} is: {gcd}") # 최소 공배수 계산 # 최소 공배수는 두 수의 곱을 최대 공약수로 나눈 값입니다. lcm = a * b // gcd print(f"The Least Common Multiple (LCM) of {a} and {b} is: {lcm}") # The Greatest Common Divisor (GCD) of 24 and 36 is: 12 # The Least Common Multiple (LCM) of 24 and 36 is: 72 import math print(math.factorial(5)) # 5 팩토리얼 출력 print(math.sqrt(7)) # 7의 제곱근 출력 print(math.gcd(21,14)) # 21과 14의 최대 공약수 , 7 print(math.pi) # 파이 출력 print(math.e) # 자연상수 출력 ``` **문자를 ASCII/유니코드 값으로 변환** ```python= char = 'A' num = ord(char) print(num) # 출력: 65 ``` **숫자로부터 문자로의 변환** ```python= num = 65 char = chr(num) print(char) # 출력: 'A' ```