1. 문제: https://www.acmicpc.net/problem/10799
이 문제는 인접한 쌍이 레이저, 여는 괄호와 닫는 괄호로 쇠막대기의 왼쪽과 오른쪽 끝의 쌍을 이룬다는 점에서 "스택"을 떠올렸다.
그러나 규칙을 찾는 데 어려움을 겪고 제한 시간내에 풀지는 못했다 🥲
따라서 다른 사람의 풀이를 보고 이해한 바를 다시금 정리하고 문제를 풀어보았다.
✅ 풀이
이 규칙대로 코드를 짜면 다음과 같다.
pipelines = input()
stack = []
answer = 0
for idx, p in enumerate(pipelines):
if p == "(": # 1
stack.append("(")
else:
if pipelines[idx-1] == "(": # 2. 레이저인 경우
stack.pop() # 3. 레이저 쌍이므로 pop
answer += len(stack) # 4. 쇠막대의 갯수만큼 더함
else:
stack.pop()
answer += 1 # 5. 쇠막대의 끝을 더함
print(answer)
1) pipelines의 배열에서 "("는 스택에 넣어 쇠막대기를 쌓기 시작한다.
2) 레이저는 반드시 인접하여 "()"를 이루는 쌍이므로, 바로 이전값과 비교해야한다.
3) 이 때 레이저를 이루는 경우에 stack에서 제외 후
4) 남은 쇠막대기의 갯수만큼 더해준다. (len(stack))
5) 인접한 ()가 아닌데 ")"를 마주친 경우는 쇠막대기의 끝이므로 이 경우 + 1을 해준다.
2. 문제: https://codesignal.com/learn/paths/fundamental-coding-interview-preparation-with-python
1) 알파벳 변환 문제 1
def encrypt_string(text):
encrypted = []
for c in text:
# TODO: Check if `c` is a letter different from 'z' and 'Z'. If so, increment by 1.
# If 'c' is 'z', change it to 'a'. If 'c' is 'Z', change it to 'A'.
# Otherwise, keep 'c' unchanged and add it to the encrypted list.
return ''.join(encrypted)
# Encrypt the string "Hello, Python!" by shifting each letter in the alphabet one by one.
encrypted_text = encrypt_string("Hello, Python!")
print("The encrypted text is:", encrypted_text) # Should print out "Ifmmp, Qzuipo!"
✅ 풀이
ord(알파벳) = 알파벳 순서 인덱스
chr(정수) = 인덱스에 해당하는 알파벳
위 코드를 활용하여 풀이하면 다음과 같다.
def encrypt_string(text):
encrypted = []
for c in text:
# TODO: Check if `c` is a letter different from 'z' and 'Z'. If so, increment by 1.
# If 'c' is 'z', change it to 'a'. If 'c' is 'Z', change it to 'A'.
# Otherwise, keep 'c' unchanged and add it to the encrypted list.
if 'a'<=c<'z' or 'A'<=c<'Z':
encrypted.append(chr(ord(c) + 1))
elif c == 'z':
encrypted.append('a')
elif c == 'Z':
encrypted.append('A')
else:
encrypted.append(c)
return ''.join(encrypted)
# Encrypt the string "Hello, Python!" by shifting each letter in the alphabet one by one.
encrypted_text = encrypt_string("Hello, Python!")
print("The encrypted text is:", encrypted_text) # Should print out "Ifmmp, Qzuipo!"
2) 알파벳 변환 문제 2
✅ 풀이
def encrypt_text(text):
encrypted = ""
for char in text:
if char.isalpha(): # 알파벳인 경우만 암호화
shift = 3
if char.isupper():
# 'A' 기준으로 순환 --> 알파벳 총 갯수가 26개 이므로 % 26을 통해 처음부터 순환
encrypted += chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
else:
# 'a' 기준으로 순환 --> 알파벳 총 갯수가 26개 이므로 % 26을 통해 처음부터 순환
encrypted += chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
else:
encrypted += char # 알파벳이 아니면 그대로 유지
return encrypted
# Example text to encrypt
original_text = "Hello, Python!"
# The encrypted_text function call and print statement should be the same as in the solution
encrypted_text = encrypt_text(original_text)
print(encrypted_text) # The correct output after implementing the TODO should be 'Khoor, Sbwkrq!'
ord(char) - ord('A') + shift ==> shift 이동한 문자열 인덱스 만들기
% 26 ==> z를 넘어가도 a로 다시 이동하도록 하는 순환 코드 (알파벳의 개수는 26개임)
+ ord('A') / ord('a') ==> 유니코드 순서에서 알파벳으로 이동시켜 정수를 알파벳으로 변환시킬 수 있도록 함
오늘의 배운점
- 쌍을 이루거나 순서대로 쌓는 과정이 있으면 stack을 활용하자.
- 배열의 특정 인덱스에 요소 넣기 -> list.insert(인덱스, 원소)
- list.index(element): element가 포함된 첫번째 인덱스 반환, 없으면 Value Error를 반환한다.
- ord(알파벳) = 알파벳 순서 인덱스
chr(정수) = 인덱스에 해당하는 알파벳
- 특정 범위 내 순환하고자 할 경우, % (모듈러) 기법을 사용하자.
- round(i, n) : i의 반올림 값 (n은 반올림하고자 하는 위치-1)
abs(i) : i의 절댓값
아래는 import math 필요
math.ceil(i) : i의 올림한 정수
math.floor(i) : i의 내림한 정수
math.trunc(i) : i의 소수점 부분을 버림한 정수
'⚙️ 알고리즘 > 문제풀이' 카테고리의 다른 글
99클럽 코테스터디 9일차 TIL - 백준 2437 (0) | 2025.04.10 |
---|---|
99클럽 코테스터디 8일차 TIL - 백준 9996 (0) | 2025.04.09 |
99클럽 코테스터디 6일차 TIL - 백준 4963, 백준 1012 (0) | 2025.04.08 |
[Python] 백준 11720, 11365, 16171 (0) | 2025.04.06 |
[Python] 백준 1753, 프로그래머스 게임 맵 최단거리, 프로그래머스 네트워크, 프로그래머스 배달 (0) | 2025.04.05 |