728x90
반응형
f-string 이란?
파이썬의 f-string으로 문자열 포맷팅하기
Engineering Blog by Dale Seo
www.daleseo.com
일반적인 문자열 앞에 f 또는 F 문자만 붙여주면 f-string이 됩니다.
중괄호(brace)을 사용하면 f-string 안 에 파이썬의 표현식(expression)을 삽입할 수 있는데요.
문자열 안에 어떤 변수나 표현식을 삽입할 때 f-string의 진가가 발휘되기 시작합니다.
f-string 사용 예시
main.py
from collections import deque
from subway_graph import *
def bfs(graph, start_node):
"""최단 경로용 bfs 함수"""
queue = deque() # 빈 큐 생성
# 모든 노드를 방문하지 않은 노드로 표시, 모든 predecessor는 None으로 초기화
for station_node in graph.values():
station_node.visited = False
station_node.predecessor = None
# 시작점 노드를 방문 표시한 후 큐에 넣어준다
start_node.visited = True
queue.append(start_node)
while queue: # 큐에 노드가 있을 때까지
current_station = queue.popleft() # 큐의 가장 앞 데이터를 갖고 온다
for neighbor in current_station.adjacent_stations: # 인접한 노드를 돌면서
if not neighbor.visited: # 방문하지 않은 노드면
neighbor.visited = True # 방문 표시를 하고
neighbor.predecessor = current_station # 이 노드가 어디서 왔는지 표시
queue.append(neighbor) # 큐에 넣는다
def back_track(destination_node):
"""최단 경로를 찾기 위한 back tracking 함수"""
res_str = "" # 리턴할 결과 문자열
temp = destination_node # 도착 노드에서 시작 노드까지 찾아가는 데 사용할 변수
# 시작 노드까지 갈 때까지
while temp is not None:
res_str = f"{temp.station_name} {res_str}" # 결과 문자열에 역 이름을 더하고
temp = temp.predecessor # temp를 다음 노드로 바꿔준다
return res_str
# 테스트 코드
stations = create_station_graph("./new_stations.txt") # stations.txt 파일로 그래프를 만든다
bfs(stations, stations["을지로3가"]) # 지하철 그래프에서 을지로3가역을 시작 노드로 bfs 실행
print(back_track(stations["강동구청"])) # 을지로3가에서 강동구청역까지 최단 경로 출력
subway_graph.py
class StationNode:
"""지하철 역을 나타내는 역"""
def __init__(self, station_name):
self.station_name = station_name
self.adjacent_stations = []
self.visited = False
def add_connection(self, station):
"""파라미터로 받은 역과 엣지를 만들어주는 메소드"""
self.adjacent_stations.append(station)
station.adjacent_stations.append(self)
def create_station_graph(input_file):
stations = {}
# 일반 텍스트 파일을 여는 코드
with open(input_file) as stations_raw_file:
for line in stations_raw_file: # 파일을 한 줄씩 받아온다
previous_station = None # 엣지를 저장하기 위한 변수
raw_data = line.strip().split("-")
for name in raw_data:
station_name = name.strip()
if station_name not in stations:
current_station = StationNode(station_name)
stations[station_name] = current_station
else:
current_station = stations[station_name]
if previous_station is not None:
current_station.add_connection(previous_station)
previous_station = current_station
return stations
728x90
반응형
'백엔드' 카테고리의 다른 글
[자격증] ADSP : 2024년 시험 일정 / 불합격 후기 (1) | 2024.01.09 |
---|---|
[자격증] 리눅스마스터 1급/2급 : 2024년 시험일정 (0) | 2024.01.09 |
[Spring] Unknown return value type: java.lang.Boolean (0) | 2023.11.05 |
[spring-boot] 포트 2개로 띄우기 (0) | 2023.10.29 |
[Redis] Spring-boot에서 gradle에 Redis설정해도 실행 안되는 이유(window) (0) | 2023.10.25 |