본문 바로가기

Programming/Phython

파이썬 알고리즘

반응형

입출력 메서드

1. input()은 항상 문자열을 반환 -> 정수를 받으려면 변환필요

cnt = int(input("정수 입력: "))  # 문자열을 정수로 변환

 

문자열

1. reversed() 메서드 -> 문자열을 직접 뒤집지 않기 때문에 리스트로 변환해 사용

s = "Hello"
reversed_s = "".join(reversed(s))
print(reversed_s)  # "olleH"

2. 문자열은 불변이므로, 리스트로 변환필요 list(strList())

s = "Hello"
lst = list(s)  # 리스트로 변환
# 리스트 조작
lst[0] = 'h'
s = "".join(lst)  # 다시 문자열로 변환
print(s)  # "hello"

 

자료구조

더보기

 

0.배열
import array

# 1. array() - 새로운 배열 생성
arr = array.array('i', [1, 2, 3, 4, 5])

# 2. append(x) - 배열의 끝에 x 추가
arr.append(6)

# 3. extend(iterable) - 배열의 끝에 iterable 추가
arr.extend([7, 8])

# 4. insert(i, x) - i 위치에 x 삽입
arr.insert(0, 0)

# 5. remove(x) - 배열에서 첫 번째로 발견되는 x 제거
arr.remove(3)

# 6. pop([i]) - i 위치의 요소 제거 및 반환
removed_value = arr.pop()  # 마지막 요소 제거
# or
# removed_value = arr.pop(0)  # 첫 번째 요소 제거

# 7. index(x[, start[, end]]) - x의 인덱스 반환
index_of_2 = arr.index(2)

# 8. count(x) - x의 개수 반환
count_of_5 = arr.count(5)

# 9. reverse() - 배열의 요소를 반대로 뒤집기
arr.reverse()

# 10. tolist() - 배열을 리스트로 변환
list_from_array = arr.tolist()

# 11. byteswap() - 배열의 모든 요소의 바이트 순서 뒤집기
arr.byteswap()

# 12. fill(value) - 배열의 모든 요소를 value로 설정
arr.fill(0)

# 13. fromlist(list) - 리스트의 요소를 배열에 추가
arr.fromlist([1, 2, 3])

# 14. frombytes(bytes) - 바이트 객체를 사용하여 배열을 채우기
arr.frombytes(b'\x01\x02\x03')

# 15. tofile(file) - 배열의 요소를 파일에 작성
with open('output.bin', 'wb') as f:
    arr.tofile(f)

# 16. fromfile(file, n) - 파일에서 n개의 요소를 읽어 배열에 추가
with open('output.bin', 'rb') as f:
    new_arr = array.array('i')
    new_arr.fromfile(f, 5)  # 5개의 요소 읽기

# 배열 출력
print("현재 배열:", arr)


1. 리스트는 []

# 리스트 사용 예제
class ListExample:
    def __init__(self):
        self.data = []

    def add(self, item):
        """리스트에 아이템을 추가합니다."""
        self.data.append(item)

    def remove(self, item):
        """리스트에서 아이템을 제거합니다. 아이템이 존재하지 않으면 ValueError 발생."""
        self.data.remove(item)

    def pop(self, index=-1):
        """주어진 인덱스의 아이템을 제거하고 반환합니다. 인덱스를 주지 않으면 마지막 아이템을 반환합니다."""
        return self.data.pop(index)

    def get(self, index):
        """주어진 인덱스의 아이템을 반환합니다. 인덱스가 범위를 벗어나면 IndexError 발생."""
        return self.data[index]

    def contains(self, item):
        """주어진 아이템이 리스트에 존재하는지 확인합니다."""
        return item in self.data

    def size(self):
        """리스트의 크기(아이템 개수)를 반환합니다."""
        return len(self.data)

    def clear(self):
        """리스트의 모든 아이템을 제거합니다."""
        self.data.clear()

    def index(self, item):
        """주어진 아이템의 인덱스를 반환합니다. 아이템이 존재하지 않으면 ValueError 발생."""
        return self.data.index(item)

    def sort(self, reverse=False):
        """리스트를 정렬합니다. reverse가 True이면 내림차순 정렬합니다."""
        self.data.sort(reverse=reverse)

    def reverse(self):
        """리스트의 요소를 역순으로 뒤집습니다."""
        self.data.reverse()

    def display(self):
        """리스트의 현재 상태를 출력합니다."""
        return self.data

# 리스트 사용 예제
if __name__ == "__main__":
    list_example = ListExample()
    
    list_example.add(1)
    list_example.add(2)
    list_example.add(3)
    
    print("리스트 현재 상태:", list_example.display())  # [1, 2, 3]
    print("리스트 크기:", list_example.size())          # 3
    
    list_example.remove(2)
    print("리스트 현재 상태 (2 제거 후):", list_example.display())  # [1, 3]
    
    list_example.add(4)
    list_example.add(5)
    print("리스트 현재 상태:", list_example.display())  # [1, 3, 4, 5]
    
    print("pop된 아이템:", list_example.pop())          # 5
    print("리스트 현재 상태:", list_example.display())  # [1, 3, 4]
    
    print("아이템 1의 인덱스:", list_example.index(1))  # 0
    list_example.sort()
    print("리스트 정렬 후:", list_example.display())    # [1, 3, 4]
    
    list_example.reverse()


2. 딕셔너리는 {} 

> 일반 딕셔너리가 삽입 순서를 유지한다. 세트의 대안으로 키를 딕셔너리로 사용

# 딕셔너리 사용 예제
class DictionaryExample:
    def __init__(self):
        self.data = {}

    def add(self, key, value):
        """키와 값을 딕셔너리에 추가합니다."""
        self.data[key] = value

    def get(self, key):
        """주어진 키에 해당하는 값을 반환합니다. 키가 존재하지 않으면 None을 반환합니다."""
        return self.data.get(key, None)

    def remove(self, key):
        """주어진 키와 해당 값을 딕셔너리에서 제거합니다."""
        if key in self.data:
            del self.data[key]

    def contains(self, key):
        """주어진 키가 딕셔너리에 존재하는지 확인합니다."""
        return key in self.data

    def size(self):
        """딕셔너리의 크기(아이템 개수)를 반환합니다."""
        return len(self.data)

    def keys(self):
        """딕셔너리의 모든 키를 리스트로 반환합니다."""
        return list(self.data.keys())

    def values(self):
        """딕셔너리의 모든 값을 리스트로 반환합니다."""
        return list(self.data.values())

    def items(self):
        """딕셔너리의 모든 키-값 쌍을 리스트로 반환합니다."""
        return list(self.data.items())

    def clear(self):
        """딕셔너리의 모든 아이템을 제거합니다."""
        self.data.clear()

    def display(self):
        """딕셔너리의 현재 상태를 출력합니다."""
        return self.data

# 딕셔너리 사용 예제
if __name__ == "__main__":
    dict_example = DictionaryExample()
    
    dict_example.add("name", "Alice")
    dict_example.add("age", 30)
    dict_example.add("city", "New York")
    
    print("딕셔너리 현재 상태:", dict_example.display())  # {'name': 'Alice', 'age': 30, 'city': 'New York'}
    print("이름:", dict_example.get("name"))  # Alice
    print("딕셔너리 크기:", dict_example.size())  # 3
    print("모든 키:", dict_example.keys())  # ['name', 'age', 'city']
    print("모든 값:", dict_example.values())  # ['Alice', 30, 'New York']
    print("모든 아이템:", dict_example.items())  # [('name', 'Alice'), ('age', 30), ('city', 'New York')]
    
    dict_example.remove("age")
    print("딕셔너리 현재 상태 (age 제거 후):", dict_example.display())  # {'name': 'Alice', 'city': 'New York'}
    
    print("딕셔너리에 'age' 존재 여부:", dict_example.contains("age"))  # False
    dict_example.clear()
    print("딕셔너리 현재 상태 (초기화 후):", dict_example.display())  # {}
3. 큐

from collections import deque

class Queue:
    def __init__(self):
        self.queue = deque()

    def is_empty(self):
        """큐가 비어있는지 확인합니다."""
        return len(self.queue) == 0

    def enqueue(self, item):
        """큐에 아이템을 추가합니다."""
        self.queue.append(item)

    def dequeue(self):
        """큐에서 아이템을 제거하고 반환합니다. 큐가 비어있으면 None을 반환합니다."""
        return self.queue.popleft() if not self.is_empty() else None

    def peek(self):
        """큐의 가장 앞 아이템을 반환합니다. 큐가 비어있으면 None을 반환합니다."""
        return self.queue[0] if not self.is_empty() else None

    def size(self):
        """큐의 현재 크기를 반환합니다."""
        return len(self.queue)

    def display(self):
        """큐의 현재 상태를 출력합니다."""
        return list(self.queue)

# 큐 사용 예제
if __name__ == "__main__":
    queue = Queue()
    
    print("큐 비어있음:", queue.is_empty())  # True
    queue.enqueue(1)
    queue.enqueue(2)
    queue.enqueue(3)
    
    print("큐 현재 상태:", queue.display())  # [1, 2, 3]
    print("큐 크기:", queue.size())          # 3
    print("가장 앞의 아이템:", queue.peek())  # 1
    print("디큐된 아이템:", queue.dequeue())  # 1
    print("큐 현재 상태:", queue.display())  # [2, 3]
    print("큐 비어있음:", queue.is_empty())  # False


4.스택

# 스택 구현을 위한 코드 예제

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        """스택이 비어있는지 확인합니다."""
        return len(self.items) == 0

    def push(self, item):
        """스택에 아이템을 추가합니다."""
        self.items.append(item)

    def pop(self):
        """스택에서 아이템을 제거하고 반환합니다. 스택이 비어있으면 None을 반환합니다."""
        return self.items.pop() if not self.is_empty() else None

    def peek(self):
        """스택의 가장 위 아이템을 반환합니다. 스택이 비어있으면 None을 반환합니다."""
        return self.items[-1] if not self.is_empty() else None

    def size(self):
        """스택의 현재 크기를 반환합니다."""
        return len(self.items)

    def display(self):
        """스택의 현재 상태를 출력합니다."""
        return self.items

# 스택 사용 예제
if __name__ == "__main__":
    stack = Stack()
    
    print("스택 비어있음:", stack.is_empty())  # True
    stack.push(1)
    stack.push(2)
    stack.push(3)
    print("스택 현재 상태:", stack.display())  # [1, 2, 3]
    print("스택 크기:", stack.size())          # 3
    print("가장 위의 아이템:", stack.peek())   # 3
    print("팝된 아이템:", stack.pop())          # 3
    print("스택 현재 상태:", stack.display())  # [1, 2]
    print("스택 비어있음:", stack.is_empty())  # False


5.힙

import heapq

# 힙 사용 예제
class Heap:
    def __init__(self):
        self.heap = []

    def push(self, item):
        """힙에 아이템 추가"""
        heapq.heappush(self.heap, item)

    def pop(self):
        """힙에서 가장 작은 아이템 제거하고 반환"""
        return heapq.heappop(self.heap) if self.heap else None

    def peek(self):
        """힙의 가장 작은 아이템 반환 (제거하지 않음)"""
        return self.heap[0] if self.heap else None

    def heapify(self, iterable):
        """주어진 iterable을 힙으로 변환"""
        self.heap = list(iterable)
        heapq.heapify(self.heap)

    def nlargest(self, n):
        """힙에서 가장 큰 n개의 아이템 반환"""
        return heapq.nlargest(n, self.heap)

    def nsmallest(self, n):
        """힙에서 가장 작은 n개의 아이템 반환"""
        return heapq.nsmallest(n, self.heap)

    def size(self):
        """힙의 크기 반환"""
        return len(self.heap)

    def display(self):
        """힙의 현재 상태 출력"""
        return self.heap

# 힙 사용 예제
if __name__ == "__main__":
    heap = Heap()
    
    heap.push(5)
    heap.push(1)
    heap.push(3)
    
    print("힙 현재 상태:", heap.display())  # 출력: [1, 5, 3]
    print("가장 작은 아이템:", heap.peek())  # 출력: 1
    print("팝된 아이템:", heap.pop())         # 출력: 1
    print("힙 현재 상태:", heap.display())  # 출력: [3, 5]
    print("가장 큰 2개 아이템:", heap.nlargest(2))  # 출력: [5, 3]
    print("가장 작은 2개 아이템:", heap.nsmallest(2))  # 출력: [3, 5]
    print("힙 크기:", heap.size())          # 출력: 2

    # 힙 변환 예제
    heap.heapify([10, 20, 15, 30])
    print("힙화된 상태:", heap.display())  # 출력: [10, 20, 15, 30]
힙 예시

힙(Heap)은 주로 우선순위 큐(Priority Queue)와 같은 데이터 구조를 구현하는 데 사용됩니다. 다양한 상황에서 활용할 수 있는 몇 가지 예시를 소개하겠습니다.

1. 우선순위 큐
힙을 사용하여 우선순위 큐를 구현할 수 있습니다. 이 큐는 가장 높은 우선순위를 가진 요소가 먼저 처리됩니다.

import heapq

class PriorityQueue:
    def __init__(self):
        self.heap = []

    def push(self, item, priority):
        # 우선순위가 낮을수록 높은 우선순위로 설정
        heapq.heappush(self.heap, (priority, item))

    def pop(self):
        return heapq.heappop(self.heap)[1] if self.heap else None

# 사용 예
pq = PriorityQueue()
pq.push("task1", 3)
pq.push("task2", 1)
pq.push("task3", 2)

print(pq.pop())  # 출력: task2 (우선순위가 가장 낮음)
print(pq.pop())  # 출력: task3
print(pq.pop())  # 출력: task1
2. 최솟값 또는 최댓값 찾기
힙을 사용하여 데이터셋에서 최솟값 또는 최댓값을 효율적으로 찾을 수 있습니다.

import heapq

numbers = [5, 1, 9, 3, 7]
min_value = heapq.nsmallest(1, numbers)[0]  # 최솟값
max_value = heapq.nlargest(1, numbers)[0]   # 최댓값

print("최솟값:", min_value)  # 출력: 1
print("최댓값:", max_value)  # 출력: 9
3. K번째 최솟값 찾기
주어진 리스트에서 K번째 최솟값을 찾는 문제를 해결할 수 있습니다.

import heapq

def kth_smallest(arr, k):
    return heapq.nsmallest(k, arr)[-1]

numbers = [5, 1, 9, 3, 7]
k = 2
print(f"{k}번째 최솟값:", kth_smallest(numbers, k))  # 출력: 3
4. 병합 K개의 정렬된 리스트
K개의 정렬된 리스트를 병합하는 문제에서 힙을 사용할 수 있습니다.

import heapq

def merge_k_sorted_lists(lists):
    heap = []
    for i, lst in enumerate(lists):
        if lst:
            heapq.heappush(heap, (lst[0], i, 0))  # (값, 리스트 인덱스, 값 인덱스)

    result = []
    while heap:
        val, list_idx, element_idx = heapq.heappop(heap)
        result.append(val)

        if element_idx + 1 < len(lists[list_idx]):
            next_tuple = (lists[list_idx][element_idx + 1], list_idx, element_idx + 1)
            heapq.heappush(heap, next_tuple)

    return result

lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
print("병합된 리스트:", merge_k_sorted_lists(lists))  # 출력: [1, 1, 2, 3, 4, 4, 5, 6]
5. K개의 가장 큰 요소 찾기
리스트에서 K개의 가장 큰 요소를 찾는 예시입니다.

import heapq

def k_largest_elements(arr, k):
    return heapq.nlargest(k, arr)

numbers = [5, 1, 9, 3, 7]
k = 3
print(f"{k}개의 가장 큰 요소:", k_largest_elements(numbers, k))  # 출력: [9, 7, 5]


*heapq

import heapq

# 힙 사용 예제
class HeapExample:
    def __init__(self):
        self.heap = []

    def push(self, item):
        """아이템을 힙에 추가합니다."""
        heapq.heappush(self.heap, item)

    def pop(self):
        """최소값을 제거하고 반환합니다."""
        return heapq.heappop(self.heap)

    def peek(self):
        """최소값을 반환하되 제거하지 않습니다."""
        return self.heap[0] if self.heap else None

    def size(self):
        """힙의 크기를 반환합니다."""
        return len(self.heap)

    def replace(self, item):
        """최소값을 제거하고 새 아이템을 추가합니다. 반환값은 제거된 최소값입니다."""
        return heapq.heapreplace(self.heap, item)

    def pushpop(self, item):
        """아이템을 힙에 추가한 후 최소값을 제거하고 반환합니다."""
        return heapq.heappushpop(self.heap, item)

    def build_heap(self, iterable):
        """주어진 iterable로부터 힙을 만듭니다."""
        self.heap = list(iterable)
        heapq.heapify(self.heap)

    def display(self):
        """힙의 현재 상태를 출력합니다."""
        return self.heap

# 힙 사용 예제
if __name__ == "__main__":
    heap_example = HeapExample()
    
    heap_example.push(3)
    heap_example.push(1)
    heap_example.push(4)
    heap_example.push(1)
    heap_example.push(5)

    print("힙 현재 상태:", heap_example.display())  # [1, 1, 4, 3, 5]
    print("최소값 제거 및 반환:", heap_example.pop())  # 1
    print("힙 현재 상태:", heap_example.display())  # [1, 3, 4, 5]
    print("최소값 보기 (제거하지 않음):", heap_example.peek())  # 1
    
    heap_example.replace(2)
    print("힙 현재 상태 (2로 교체 후):", heap_example.display())  # [2, 3, 4, 5]

    print("pushpop 결과:", heap_example.pushpop(0))  # 2 (0 추가 후 2 제거)
    print("힙 현재 상태:", heap_example.display())  # [0, 3, 4, 5]

    heap_example.build_heap([8, 6, 7])
    print("새로운 힙 상태 (8, 6, 7로부터):", heap_example.display())  # [6, 8, 7]


6.연결리스트

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

 

반복문

1. 뒤집어서 돌기 for i in range(len(str1) - 1, -1, -1): # 인덱스를 len(str1) - 1부터 0까지 감소

s = "Hello"
for i in range(len(s) - 1, -1, -1):
    print(s[i], end="")  # "olleH"

 

 

 

슬라이싱

더보기

슬라이싱(Slicing)은 파이썬에서 문자열, 리스트, 튜플 등의 시퀀스 데이터 타입의 특정 부분을 쉽게 추출하는 방법입니다. 슬라이싱을 사용하면 원하는 인덱스 범위의 요소를 선택할 수 있습니다.

기본 구문

슬라이싱의 기본 구문은 다음과 같습니다:

sequence[start:end:step]
  • start: 슬라이스를 시작할 인덱스 (포함).
  • end: 슬라이스를 끝낼 인덱스 (미포함).
  • step: 인덱스를 증가시키는 간격 (기본값은 1).

예시

  1. 문자열 슬라이싱:
    s = "Hello, World!" 
    print(s[0:5]) # "Hello" 
    print(s[7:]) # "World!" 
    print(s[:5]) # "Hello" 
    print(s[::2]) # "Hlo ol!" (2칸 간격으로 선택)


  2. 리스트 슬라이싱:
    lst = [0, 1, 2, 3, 4, 5, 6] 
    print(lst[1:4]) # [1, 2, 3] 
    print(lst[:3]) # [0, 1, 2] 
    print(lst[3:]) # [3, 4, 5, 6] 
    print(lst[::2]) # [0, 2, 4, 6] (2칸 간격으로 선택)


  3. 부정적 인덱스:
    슬라이싱에서는 부정적 인덱스를 사용할 수도 있습니다. 이 경우, -1은 마지막 요소를 의미합니다.
    s = "Hello, World!" 
    print(s[-6:]) # " World!" 
    print(s[:-1]) # "Hello, World" 
    print(s[::-1]) # "!dlroW ,olleH" (역순)
    [:-1]: 마지막 요소를 제외한 모든 요소를 반환합니다.
    [::-1]: 모든 요소를 역순으로 반환합니다.

  4. 중첩 슬라이싱
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    print(matrix[1:3])         # [[4, 5, 6], [7, 8, 9]]
    print(matrix[1:3][0])      # [4, 5, 6]



  5. 예시
    문자열 반전
    def reverse_string(s):
        return s[::-1]
    
    # 예시 사용
    print(reverse_string("Hello"))  # "olleH"
     
    특정 부분 추출
    def extract_date(date_string):
        year, month, day = date_string.split('-')
        return year, month, day
    
    # 예시 사용
    print(extract_date("2023-10-05"))  # ('2023', '10', '05')

    짝수 인덱스 요소 추출
    def even_index_elements(lst):
        return lst[::2]
    
    # 예시 사용
    print(even_index_elements([1, 2, 3, 4, 5, 6]))  # [1, 3, 5]

    문자열 자르기
    def slice_string(s, start, end):
        return s[start:end]
    
    # 예시 사용
    print(slice_string("Hello, World!", 7, 12))  # "World"

    최댓값과 최솟값
    def exclude_min_max(lst):
        lst_sorted = sorted(lst)
        return lst_sorted[1:-1]  # 최솟값과 최댓값 제외
    
    # 예시 사용
    print(exclude_min_max([3, 1, 4, 1, 5, 9, 2]))  # [2, 3, 4, 5, 9]

    특정 문자로 문자열 나누기
    def split_string(s, delimiter, index):
        parts = s.split(delimiter)
        return parts[index] if index < len(parts) else None
    
    # 예시 사용
    print(split_string("apple,banana,cherry", ",", 1))  # "banana"

    특정 자리수 만큼 반복해서 자르기
    예제
    1. 기본 슬라이싱 사용설명
    • slice_string 함수:
      • 입력 문자열 s와 잘라낼 길이 length를 인자로 받습니다.
      • 리스트 컴프리헨션을 사용하여 문자열을 length 만큼 잘라냅니다.
      • range(0, len(s), length)는 문자열의 시작 인덱스에서 length 간격으로 슬라이싱을 수행합니다.
    • 출력 결과: 예를 들어, input_string이 "HelloWorld"이고 slice_length가 3일 경우, 결과는 ['Hel', 'loW', 'orl', 'd']가 됩니다.
      def slice_string(s, length):
          return [s[i:i + length] for i in range(0, len(s), length)]
      
      # 예시 사용
      input_string = "HelloWorld"
      slice_length = 3
      sliced_strings = slice_string(input_string, slice_length)
      
      print(sliced_strings)  # ['Hel', 'loW', 'orl', 'd']


    2. 문자열이 남는 경우 처리
    위 코드에서는 마지막에 남는 부분도 포함되어 있습니다. 예를 들어, HelloWorld를 3자리로 나누면 마지막에 d가 남습니다. 이를 원하지 않을 경우, 추가 조건을 넣어 필터링할 수 있습니다.
    def slice_string(s, length):
        return [s[i:i + length] for i in range(0, len(s), length) if i + length <= len(s)]
    
    # 예시 사용
    input_string = "HelloWorld"
    slice_length = 3
    sliced_strings = slice_string(input_string, slice_length)
    
    print(sliced_strings)  # ['Hel', 'loW', 'orl']


 

fstring

더보기

 

f-string(형식 문자열)은 파이썬 3.6부터 도입된 문자열 포맷팅 방법으로,

문자열 안에 변수를 직접 삽입할 수 있는 편리한 방식입니다.

s = "2023-10-05"
date = s.split('-')  # ['2023', '10', '05']
year = date[0]
month = date[1]
day = date[2]
print(f"Year: {year}, Month: {month}, Day: {day}")

 

기본 문법

f 또는 F를 문자열 앞에 붙여서 사용합니다:

name = "Alice"
age = 30
greeting = f"My name is {name} and I am {age} years old."
print(greeting)  # "My name is Alice and I am 30 years old."

중괄호 {} 사용

  • 변수 삽입: 중괄호 {} 안에 변수를 넣으면 해당 변수의 값이 삽입됩니다.
  • 표현식 사용: 중괄호 안에 표현식도 사용할 수 있습니다.
x = 5
y = 10
result = f"The sum of {x} and {y} is {x + y}."
print(result)  # "The sum of 5 and 10 is 15."

포맷 옵션

f-string에서는 형식을 지정할 수 있습니다. 예를 들어, 소수점 이하 자릿수를 지정할 수 있습니다:

pi = 3.141592653589793
formatted_pi = f"Pi rounded to two decimal places: {pi:.2f}"
print(formatted_pi)  # "Pi rounded to two decimal places: 3.14"

날짜와 시간 포맷팅

datetime 모듈을 사용하여 날짜와 시간을 포맷할 때도 유용합니다:

from datetime import datetime

now = datetime.now()
formatted_date = f"Today is {now:%Y-%m-%d %H:%M:%S}."
print(formatted_date)  # "Today is 2024-10-05 15:30:00." (현재 시간 기준)

이스케이프 문자

중괄호를 문자열에 포함시키고 싶다면 중괄호를 두 번 씁니다:

value = 42
message = f"The value is {{value}}."  # 중괄호를 이스케이프
print(message)  # "The value is {value}."

다중 줄 f-string

다중 줄 문자열에서도 사용할 수 있습니다:

name = "Bob"
age = 25
info = f"""
Name: {name}
Age: {age}
"""
print(info)

성능

f-string은 다른 포맷팅 방법보다 더 빠르며, 가독성이 뛰어납니다. Python의 다른 문자열 포맷팅 방법(예: %, str.format())과 비교할 때 더 간단하고 직관적입니다.

요약

  • 기본 사용: f"문자열 {변수}"
  • 표현식: f"{x + y}"
  • 형식 지정: f"{변수:.2f}"
  • 날짜 및 시간 포맷팅: f"{date:%Y-%m-%d}"
  • 이스케이프: f"{{}}"
  • 다중 줄: f"""\n..."""

 

리스트 컴프리핸션

더보기
[expression for item in iterable if condition]
  • expression: 리스트의 각 요소로 변환할 표현식입니다.
  • item: iterable(리스트, 튜플, 문자열 등)의 각 요소입니다.
  • iterable: 반복 가능한 객체입니다.
  • condition: (선택 사항) 특정 조건을 만족하는 경우에만 요소를 포함합니다.

리스트 컴프리헨션의 장점

  • 코드가 간결해지고 가독성이 향상됩니다.
  • 리스트를 생성할 때 더 효율적입니다.

코딩 테스트에서 자주 쓰는 리스트 컴프리헨션 예시 10가지

제곱수 리스트 생성:

squares = [x**2 for x in range(10)]
# 결과: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

짝수만 추출:

evens = [x for x in range(20) if x % 2 == 0]
# 결과: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

문자열 대문자 변환:

words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
# 결과: ['HELLO', 'WORLD', 'PYTHON']

짝수 인덱스의 요소 추출:

items = ['a', 'b', 'c', 'd', 'e']
even_index_items = [items[i] for i in range(len(items)) if i % 2 == 0]
# 결과: ['a', 'c', 'e']

2차원 리스트 평탄화:

matrix = [[1, 2, 3], [4, 5], [6]]
flat_list = [num for row in matrix for num in row]
# 결과: [1, 2, 3, 4, 5, 6]

문자열에서 모음만 추출:

sentence = "Hello, World!"
vowels = [char for char in sentence if char in 'aeiouAEIOU']
# 결과: ['e', 'o', 'o']

피타고라스 수 생성:

pythagorean_triples = [(a, b, int((a**2 + b**2)**0.5)) for a in range(1, 10) for b in range(a, 10) if (a**2 + b**2)**0.5 % 1 == 0]
# 결과: [(3, 4, 5), (6, 8, 10)]

문자열 길이 리스트 생성:

words = ["hello", "world", "python"]
lengths = [len(word) for word in words]
# 결과: [5, 5, 6]

조건에 맞는 키 값 추출:

dictionary = {'a': 1, 'b': 2, 'c': 3}
keys_with_value_above_one = [key for key, value in dictionary.items() if value > 1]
# 결과: ['b', 'c']

숫자를 문자열로 변환:

numbers = [1, 2, 3, 4]
str_numbers = [str(num) for num in numbers]
# 결과: ['1', '2', '3', '4']

 

 


https://cote.inflearn.com/contest/10/problem/01-04

cnt = int(input())
strList = []
for i in range(cnt):
  print("".join(reversed(input())))

https://cote.inflearn.com/contest/10/problem/01-05

str1 = list(input())
strAlpha=[]
for char in str1:
  if char.isalpha():
    strAlpha.append(char)

cnt =0

for i in range(len(str1)-1, -1, -1):
  if str1[i].isalpha():
    str1[i]=strAlpha[cnt]
    cnt+=1

print("".join(str1))

https://cote.inflearn.com/contest/10/problem/01-06

strList = list(input())
setList = {}

for char in strList:
  setList[char]=None;

print("".join(setList.keys()))

https://cote.inflearn.com/contest/10/problem/01-07

str1 = input()

strComp= "".join(reversed(str1))

if str1.casefold() == strComp.casefold():
  print("YES")
else:
  print("NO")

https://cote.inflearn.com/contest/10/problem/01-08

str1 =input()
str2 =""
str3 =""
for char in str1:
  if char.isalpha():
    str2+=char

str3 = str2[::-1]

if str2.casefold() == str3.casefold():
  print("YES")
else:
  print("NO")

 


https://cote.inflearn.com/contest/10/problem/01-10

import array

# 첫 번째 문자열과 두 번째 문자열(문자)을 입력받습니다.
str1, str2 = input().split()

# 거리 배열을 무한대로 초기화합니다.
arr = array.array('i', [100] * len(str1))

# str2의 모든 인덱스를 찾아서 거리 계산
for i in range(len(str1)):
    if str1[i] == str2:
        # str2가 있는 인덱스 i에 대해 모든 거리 업데이트
        for j in range(len(str1)):
            arr[j] = min(arr[j], abs(i - j))

# 결과 출력
print(" ".join(map(str, arr)))

 


https://cote.inflearn.com/contest/10/problem/01-11

str1 = input()
result = ''
cnt = 1

# 문자열의 첫 번째 문자를 초기화
previous_char = str1[0]  # 첫 번째 문자로 초기화

for i in range(1, len(str1)):
    char = str1[i]
    if char == previous_char:
        cnt += 1  # 이전 문자와 같으면 카운트 증가
    else:
        # 이전 문자와 다르면 결과에 추가
        result += previous_char
        if cnt > 1:
            result += str(cnt)  # 카운트가 1보다 크면 추가
        cnt = 1  # 카운트 초기화
    previous_char = char  # 이전 문자 업데이트

# 마지막 문자 추가
result += previous_char
if cnt > 1:
    result += str(cnt)

print(result)

 


문자열 남는 경우 처리 + 아스키코드로 변환 + 이진수 변환

https://cote.inflearn.com/contest/10/problem/01-12

# 사용자로부터 두 줄의 입력을 받습니다.
number = int(input())  # 첫 번째 입력값은 정수로 변환
string = input().replace('#', '1').replace('*', '0')  # 두 번째 입력값은 문자열

def slice_string(s, length):
    return [s[i:i + length] for i in range(0, len(s), length) if i + length <= len(s)]

# 주어진 숫자에 따라 문자열을 슬라이스합니다.
sliced_strings = slice_string(string, 7)

# 결과 출력
for char in sliced_strings:
    print(chr(int(char,2)), end="")

 

반응형

'Programming > Phython' 카테고리의 다른 글

Numpy  (1) 2024.10.05
[파이썬] 프로그램의 입력과 출력 정리  (0) 2021.02.16
[파이썬] 15. 파일 읽고 쓰기  (0) 2021.02.15
[파이썬] 14. 사용자 입력과 출력  (0) 2021.02.15
[파이썬] 13. 함수  (0) 2021.02.14