Skip to content

[월요일] 4주차 구현 - 1 + 스택, 큐  #8

Open

Description

@SuwonPabby

🔥 월요일 4주차 - 구현 1, Stack, Queue 🔥

Contents

1. 자료구조에 대한 직관 (큐, 스택)
2. 카드2 빠른 풀이 -> 연산 횟수를 줄여라
3. 크로아티아 알파벳의 다양한 풀이
4. 색종이 -> Representation
5. 색종이 -> 이차원 리스트 사용 시 주의점들
6. 시간 측정해보는 문법

1. 자료구조에 대한 직관 (큐, 스택)

Queue

  • 작업들이 줄 서 있는 모습을 상상!
  • 들어온 순서대로 처리되는 것이 보장되어야 하는 상황일 때 사용
  • 파이썬에서 구현 => deque 자료 구조 사용
from collections import deque
queue = deque()  #queue = deque([1, 2, 3]) 이렇게 리스트를 deque화 시킬 수도 있음!
queue.append("task1")
queue.append("task2")
# popleft, pop 메서드는 pop되는 값을 리턴함!
# 그러나 파이썬에서는 값이 리턴되는 함수이더라도 걍 실행만 시킬 수 있음!
queue.popleft()
b = queue.popleft()

Stack

  • 접시가 쌓여있는 모습을 상상!
  • 나중에 들어온 놈이 먼저 나가는 것이 보장되어야 하는 상황일 때 사용
  • 함수의 호출 역시 Stack 구조로 이루어짐! 그래서 Call Stack 이라고 부름!
  • 파이썬에서 구현 => List 자료 구조 사용 (Deque을 써도 되긴 하지만.. 굳이 그럴 필요는 없으니)
stack = []
stack.append(1)
stack.append(2)
stack.pop()
b = stack.pop()

Deque

  • popleft, appendleft, pop, append 연산 모두 시간복잡도 O(1)을 보장함
  • 그와 반대로 List는 popleft와 appendleft가 O(n), pop과 append가 O(1)임
  • 그래서 스택은 List를 그냥 쓰면 되고 큐는 deque을 사용해야 하는 것!

2. 카드2 빠른 풀이

  • 카드2는 큐를 이용해 모든 경우를 시뮬레이션을 돌릴 수 있지만
  • 규칙성을 이용하면 계산 횟수를 더 줄일 수 있음!
  • n = 홀수일 때와 짝수일 때를 나누어 카드 빼는 과정을 한 바퀴 돌렸을 때 어떻게 되는지 생각해보자!
  • 그러면 0, 2, 4.... 번째 카드는 무조건 버려지고 나머지 카드 순서만 홀수일 때, 짝수일 때로 나누어서 처리를 해주기만 하면 된다는 것을 알 수 있음!
  • 참고 코드 -> 건희님 코드 (금요일반)
import sys

input = sys.stdin.readline
N = int(input())
cards = [i for i in range(1, N+1)]

def solution_using_queue(cards):
    while len(cards) > 1:
        cards.pop(0)
        cards.append(cards.pop(0))
    return cards[0]

def solution(cards):
    while len(cards) > 1:
        n = len(cards)
        cards = cards[1::2]
        if n % 2 == 1:
            cards.append(cards.pop(0))
    return cards[0]

print(solution(cards))

3. 크로아티아 알파벳의 다양한 풀이

1. 직접 구현 방식

  1. 한 단어씩 따지면서 푸는 풀이 (희주님 풀이)
import sys

alph = sys.stdin.readline().strip()

# ALPH = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']
answer = 0
i = 0
L = len(alph)

while i < L:
    if i+1 < L: # 다음 알파벳이 있는지 확인
        if alph[i] == 'c': # c=, c-
            if alph[i+1] == '=' or alph[i+1] == '-':
                i += 2
            else: # 해당 안되는 경우는 한 글자
                i += 1
        elif alph[i] == 'd': # d-, dz=
            if alph[i+1] == '-':
                i += 2
            elif i+2 < L: # 다음 알파벳이 있는지 확인
                if alph[i+1] == 'z' and alph[i+2] == '=':
                    i += 3
                else:
                    i += 1
            else: 
                i += 1
        elif alph[i] == 'l': # lj
            if alph[i+1] == 'j':
                i += 2
            else:
                i += 1
        elif alph[i] == 'n': # nj
            if alph[i+1] == 'j':
                i += 2
            else:
                i += 1
        elif alph[i] == 's': # s=
            if alph[i+1] == '=':
                i += 2
            else:
                i += 1
        elif alph[i] == 'z': # z=
            if alph[i+1] == '=':
                i += 2
            else:
                i += 1
        else:
            i += 1
        answer += 1 
        
    else: # 다음 알파벳이 없다면 (끝)
        answer += 1
        break
        
print(answer)

예준님 풀이 (금요일반)

import sys
input=sys.stdin.readline().rstrip()
num = 0

str = list(input)
length = len(str)
pointer = 0
for i in range(2):
    str.append('-')

def count_and_pop(a):
    global num, pointer
    num += 1
    pointer += a
    for i in range(a):
        str.pop(0)

while pointer < length:
    if str[0] == 'c':
        if str[1] == '=' or str[1] == '-':
            count_and_pop(2)
        else:
            count_and_pop(1)
    elif str[0] == 'd':
        if str[1] == '-':
            count_and_pop(2)
        elif str[1] == 'z' and str[2] == '=':
            count_and_pop(3)
        else:
            count_and_pop(1)
        
    elif str[0] == 'l' and str[1] == 'j':
        count_and_pop(2)
    elif str[0] == 'n' and str[1] == 'j':
        count_and_pop(2)
    elif str[0] == 's' and str[1] == '=':
        count_and_pop(2)
    elif str[0] == 's' and str[1] == '=':
        count_and_pop(2)
    elif str[0] == 'z' and str[1] == '=':
        count_and_pop(2)
    else:
        count_and_pop(1)

print(num)                
  1. 한 단어씩 따지면서 푸는 풀이 (Match 이용 풀이, 의진 풀이) (주의사항: match -> 3.10이상)
import sys
input = sys.stdin.readline

string = input().rstrip()

idx = 0
answer = 0
while idx < len(string):
    char = string[idx]
    match char:
        case "l":
            if idx + 1 < len(string) and string[idx:idx+2] == "lj":
                answer += 1
                idx += 2
            else:
                answer += 1
                idx += 1
        case "n":
            if idx + 1 < len(string) and string[idx:idx+2] == "nj":
                answer += 1
                idx += 2
            else:
                answer += 1
                idx += 1
        case "s":
            if idx + 1 < len(string) and string[idx:idx+2] == "s=":
                answer += 1
                idx += 2
            else:
                answer += 1
                idx += 1
        case "z":
            if idx + 1 < len(string) and string[idx:idx+2] == "z=":
                answer += 1
                idx += 2
            else:
                answer += 1
                idx += 1

        case "c":
            if idx + 1 < len(string):
                if string[idx:idx+2] == "c=":
                    answer += 1
                    idx += 2
                elif string[idx:idx+2] == "c-":
                    answer += 1
                    idx += 2
                else:
                    answer += 1
                    idx += 1
            else:
                answer += 1
                idx += 1

        case "d":
            if idx + 1 < len(string) and string[idx:idx+2] == "d-":
                answer += 1
                idx += 2

            elif idx + 2 < len(string) and string[idx:idx+3] == "dz=":
                answer += 1
                idx += 3
            else:
                answer += 1
                idx += 1
        case _:
            answer += 1
            idx += 1
print(answer)

2. 함수를 이용한 풀이

  1. replace 등의 문법을 이용한 풀이
    (가장 많이 나온 형태의 풀이)
croatia = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']
word = input()

for i in croatia:
    word = word.replace(i, '*')
print(len(word))
  1. regex를 이용한 풀이 (실험 결과 regex가 replace보다 조금 더 오래 걸림)(은채님 풀이)
import re

s = input()
expression = ['dz=', 'lj', 'nj', 'c=', 'c-', 'd-', 's=', 'z=']
answer = 0

for exp in expression:
    c = re.findall(exp, s)
    answer += len(c)
    s = re.sub(exp, '_', s)

s = re.sub('_', '', s)
print(answer + len(s))

4. 색종이 -> Representation

  • 색종이 문제를 2차원 리스트 Representation으로 표현하는 방법이 있었고
  • 집합 자료형 Representation으로 표현하는 방법이 있었다.
  • 2차원 리스트 Representation 의 장점은 연산이 빠르다 집합 자료형은 Union 연산의 Cost가 높음
  • 그러나 2차원 리스트 Representation은 100 X 100 의 메모리를 무조건 사용해야하나, 집합 자료형은 꼭 100x100 을 다 안써도 되므로, 색종이가 면적이 작다면 이 방식이 더 효과적일 수 있다.
  • 집합 자료형 풀이 (건희님 풀이)
import sys

input = sys.stdin.readline

N = int(input())
papers = [list(map(int, input().split())) for _ in range(N)]

def solution(papers):
    ret = 0
    board = [[0 for _ in range(100)] for _ in range(100)]
    for s_col, s_row in papers:
        for col in range(s_col, s_col+10):
            for row in range(s_row, s_row+10):
                if board[row][col] == 0:
                    board[row][col] = 1
                    ret += 1
    return ret

print(solution(papers))

checked = set()
for paper in papers:
    checked = checked.union(
    set([(i, j) for i in range(paper[0], paper[0] + 10) \
                for j in range(paper[1], paper[1] + 10)]))
print(len(checked))

5. 색종이 - 2차원 배열 다루기

  • Row와 Col 을 정확하게 설정해서 해야한다! 문제에 따라 x, y 로 나오는 경우도 있고 y, x로 나오는 경우도 있다.
  • 아래 그림을 외워두고 문제에 맞게 정확하게 어떻게 써야하는지 인지하고 (주석으로 적어놔도 좋음)
image

6. 시간 측정해보는 문법

  • 아래 문법을 이용하면 시간을 측정할 수 있다.
import time
start_time = time.time()
# 측정해 볼 로직
end_time = time.time()
elapse_time = end_time - start_time
print(elapse_time)

Activity

  1. self-assigned this
    on Sep 26, 2023
  2. added a commit that references this issue on Sep 26, 2023
  3. added 4 commits that reference this issue on Oct 1, 2023
  4. added a commit that references this issue on Oct 4, 2023
  5. added 4 commits that reference this issue on Oct 5, 2023
  6. added a commit that references this issue on Oct 6, 2023
  7. added a commit that references this issue on Oct 8, 2023
  8. added a commit that references this issue on Oct 9, 2023
  9. added a commit that references this issue on Oct 9, 2023
  10. added a commit that references this issue on Oct 12, 2023
  11. added a commit that references this issue on Oct 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions