파이썬 코테 팁

유석현(SeokHyun Yu)·2023년 10월 9일
0

정보

목록 보기
8/9
post-thumbnail

1. 문자열 또는 리스트 뒤집기:

my_string = "Hello"
my_string = my_string[::-1]  # 문자열을 뒤집습니다.
my_list = [1, 2, 3, 4]
my_list.reverse()  # 리스트를 뒤집습니다.

2. 특정 값 빼놓기:

my_list = [1, 2, 3, 4, 5]
value_to_exclude = 3
filtered_list = [x for x in my_list if x != value_to_exclude]

3. 두 배열에서 같은 갯수 찾기:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_count = len(set(list1)&set(list2))  # 교집합을 이용하여 같은 갯수 찾기

4. 짝수와 홀수 나누기:

num = 5
if num % 2 == 0:
    print("짝수")
else:
    print("홀수")

5. 리스트 끝 인덱스 사용:

my_list = [1, 2, 3, 4, 5]
last_element = my_list[-1]

6. 조건부 표현식 사용:

a = 4
result = True if a > 3 else False

7. 리스트 컴프리헨션:

my_list = [1, 2, 3, 4, 5]
result = [i * 3 for i in my_list if i % 2 == 0]

8. 내장 함수:

import math

abs_value = abs(-5)
max_value = max(1, 2, 3)
min_value = min(1, 2, 3)
sqrt_value = math.sqrt(16)

9. str() 함수:

num = 123
num_str = str(num)  # 정수를 문자열로 변환

10. 리스트 정렬:

my_list = [3, 1, 2]
my_list.sort(reverse=True)  # 내림차순으로 정렬

11. 중복된 값의 인덱스 찾기:

my_list = [1, 2, 3, 2, 4, 5, 2]
value_to_find = 2
indices = [i for i, x in enumerate(my_list) if x == value_to_find]

12. 양의 정수 확인:

num = "123"
is_positive = num.isdigit()

13. 제곱근 계산:

import math

sqrt_value = math.sqrt(25)

14. 실수 부동소수점 주의:

result = 1.1 + 2.2  # 부동소수점 연산 결과 주의

15. 정수 여부 확인:

num = 5.0
is_integer = num.is_integer()  # 실수가 정수인지 확인

16. 비트 시프트 연산:

x = 8
shifted_value = x << 1  # 2배씩 증가

17. join() 메서드:

my_list = ["Hello", "World"]
my_string = " ".join(my_list)  # 리스트의 문자열을 합침

18. 대소문자 변환:

my_string = "Hello World"
swapped_case = my_string.swapcase()  # 대소문자를 바꿈

19. 조건에 따라 문자열 변환:

my_string = "Hello World"
transformed_string = "".join([x.lower() if x.isupper() else x.upper() for x in my_string])

20. max와 min 사용:

a = 5
b = 3
max_value = max(a, b)
min_value = min(a, b)

21. in 연산자 사용:

my_list = [1, 2, 3, 4, 5]
value_to_find = 3
if value_to_find in my_list:
    print("값이 존재합니다.")

22. 문자열 메서드:

my_string = "Hello, World"
upper_case = my_string.upper()
lower_case = my_string.lower()

23. sorted() 함수:

my_list = [3, 1, 2]
sorted_list = sorted(my_list)  # 정렬된 새 리스트 반환

24. 리스트에서 특정 값 제거:

my_list = [1, 2, 3, 4, 5]
value_to_remove = 3
my_list = [x for x in my_list if x != value_to_remove]

25. 예외 케이스 고려:

num = 0
if num == 0:
    print("0입니다.")
elif num > 0:
    print("양의 정수입니다.")
else:
    print("음의 정수입니다.")

26. 이진수 변환:

binary_str = bin(10)[2:]  # 십진수를 이진수로 변환

27. 슬라이싱 최대길이 초과:

my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[:10]  # 최대길이를 초과해도 에러 발생하지 않음

28. 정렬 기준 지정:

words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=lambda word: len(word))  # 길이를 기준으로 정렬

29. 복수의 기준으로 정렬:

words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=lambda word: (len(word), word))  # 길이와 알파벳순으로 정렬

30. 딕셔너리 순회:

my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
    print(key, value)

31. DFS와 BFS에서 n*n 배열 문제 해결:

def dfs(matrix, visited, row, col):
    if row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[0]) or visited[row][col]:
        return
    visited[row][col] = True
    # 위, 아래, 왼쪽, 오른쪽으로 재귀 호출
    dfs(matrix, visited, row - 1, col)
    dfs(matrix, visited, row + 1, col)
    dfs(matrix, visited, row, col - 1)
    dfs(matrix, visited, row, col + 1)

32. 이진 탐색:

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = left + right // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1  # 찾지 못한 경우

33. 스택(Stack) 함수로 구현:

def create_stack():
    return []

def is_empty(stack):
    return len(stack) == 0

def push(stack, item):
    stack.append(item)

def pop(stack):
    if not is_empty(stack):
        return stack.pop()

def peek(stack):
    if not is_empty(stack):
        return stack[-1]

def stack_size(stack):
    return len(stack)

34. 큐(Queue)를 deque를 사용하여 구현:

from collections import deque

def create_queue():
    return deque()

def is_empty(queue):
    return len(queue) == 0

def enqueue(queue, item):
    queue.append(item)

def dequeue(queue):
    if not is_empty(queue):
        return queue.popleft()

def peek(queue):
    if not is_empty(queue):
        return queue[0]

def queue_size(queue):
    return len(queue)

35. 힙(Heap) 함수로 구현:

import heapq

def create_min_heap():
    return []

def push_min_heap(heap, item):
    heapq.heappush(heap, item)

def pop_min_heap(heap):
    if not is_empty_min_heap(heap):
        return heapq.heappop(heap)

def peek_min_heap(heap):
    if not is_empty_min_heap(heap):
        return heap[0]

def is_empty_min_heap(heap):
    return len(heap) == 0

def min_heap_size(heap):
    return len(heap)

36. nonlocal:

nonlocal은 파이썬에서 변수 범위(scope)를 나타내는 키워드 중 하나입니다. 파이썬에서 변수는 전역 변수(global variable), 지역 변수(local variable), 중첩 함수 내의 변수(nested function variable)로 나누어집니다. nonlocal은 중첩 함수에서 바깥쪽 함수의 변수를 수정하거나 참조할 때 사용됩니다.

보다 자세한 설명을 제공하기 위해 예제를 사용하겠습니다. 아래의 코드에서 outer_function 안에 x라는 변수가 정의되어 있고, inner_function에서 x를 참조하고 수정하려고 합니다.

Copy code
def outer_function():
    x = 10
    
    def inner_function():
        nonlocal x  # 중첩 함수에서 바깥쪽 함수의 변수 x를 사용하겠다고 선언
        x += 5
    
    inner_function()
    print(x)  # 출력 결과는 15가 됨

outer_function()

여기서 nonlocal 키워드를 사용하면 inner_function 내에서 x 변수가 outer_function의 변수 x를 참조하고 수정할 수 있게 됩니다. 그 결과로 inner_function에서 x를 5 증가시키고, outer_function에서 x를 출력하면 15가 나옵니다.

즉, nonlocal은 중첩 함수에서 바깥쪽 함수의 변수를 변경하거나 참조하는 데 사용되며, 이를 통해 중첩 함수가 외부 함수의 변수에 영향을 미칠 수 있습니다. 이것은 함수 간에 데이터를 공유하고 효율적으로 작업하는 데 유용한 기능 중 하나입니다.


37. global:

global은 파이썬에서 변수 범위(scope)를 나타내는 키워드 중 하나로, 전역 범위(global scope)에 있는 변수를 함수 내부에서 참조하거나 수정할 때 사용됩니다. 파이썬에서 변수는 지역 변수(local variable)와 전역 변수(global variable)로 나뉩니다. 함수 내부에서 변수를 정의하면 그 변수는 지역 범위에서만 유효하며 함수 외부에서 정의된 변수는 전역 범위에서 유효합니다. global 키워드는 전역 변수를 함수 내에서 사용하고 변경할 수 있게 합니다.

다음은 global 키워드의 사용 예제입니다:

Copy code
x = 10  # 전역 변수 x를 정의

def modify_global_variable():
    global x  # 함수 내에서 전역 변수 x를 사용하겠다고 선언
    x += 5  # 전역 변수 x를 5 증가시킴

modify_global_variable()
print(x)  # 출력 결과는 15가 됨

위의 코드에서 global 키워드를 사용하여 함수 내부에서 전역 변수 x를 참조하고 수정하였습니다. 따라서 modify_global_variable 함수 호출 후에 x의 값은 15가 됩니다.

주의할 점은 global 키워드를 사용할 때 변수 이름 앞에 global을 붙여야 한다는 것입니다. 이를 통해 파이썬은 이 변수가 전역 변수임을 인식하고 해당 변수를 전역 범위에서 찾아 수정합니다.

전역 변수를 사용하는 것은 필요할 때 유용하지만, 지나치게 많이 사용하면 코드를 이해하기 어려워질 수 있으므로 신중하게 사용해야 합니다. 함수 간에 데이터를 공유하거나 상태를 관리해야 할 때 global 키워드를 사용할 수 있습니다.

profile
Backend Engineer

0개의 댓글