Ⅰ. 프로그래밍
파이썬 달팽이 배열 값 입력
agencies
2024. 2. 18. 13:34
def prt(message):
# 입력 메시지의 길이 계산
length = len(message)
# 배열의 크기 결정 (가로, 세로)
if length ** 0.5 % 1 != 0: # 만약 메시지의 길이가 제곱수가 아니라면
size = int(length ** 0.5) + 1 # 달팽이 배열의 크기는 제곱근에 1을 더한 값
else: # 메시지의 길이가 제곱수라면
size = int(length ** 0.5) # 달팽이 배열의 크기는 제곱근
# 2차원 배열 생성
snail_array = []
for i in range(size):
inner_list = []
for j in range(size):
inner_list.append(' ')
snail_array.append(inner_list)
# 달팽이 배열에 메시지 입력
row, col = 0, 0
direction = [(0, 1), (1, 0), (0, -1), (-1, 0)]
direction_index = 0
for char in message:
snail_array[row][col] = char
next_row = row + direction[direction_index][0]
next_col = col + direction[direction_index][1]
if next_row < 0 or next_row >= size or next_col < 0 or next_col >= size or snail_array[next_row][next_col] != ' ':
direction_index = (direction_index + 1) % 4
next_row = row + direction[direction_index][0]
next_col = col + direction[direction_index][1]
row, col = next_row, next_col
# 달팽이 배열 출력
for row in snail_array:
print(' '.join(row))
# 사용자 입력 받기
msg = input("INPUT: ")
# 달팽이 배열 형태로 메시지 출력
prt(msg)