완전 탐색(Brute Force), 시뮬레이션 유형을 모두 구현 유형으로 묶어서 다루고 있다. ('이것이 취업을 위한 코딩 테스트다' -나동빈 저자-)
완전 탐색(Brute Force) : 모든 경우의 수를 주저 없이 다 계산하는 해결 방법
# 예제 4-2 시각
h = int(input())
count = 0
for i in range(h + 1):
for j in range(60):
for k in range(60):
# 매 시각 안에 '3'이 포함되어 있다면 카운트 증가
if '3' in str(i) + str(j) + str(k):
count += 1
print(count)
시뮬레이션 : 문제에서 제시한 알고리즘을 한 단계씩 차례대로 직접 수행하여 해결
# 예제 4-1 상하좌우
n = int(input())
x, y = 1, 1
plans = input().split()
#L, R, U, D에 따른 이동 방향
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
move_types = ['L', 'R', 'U', 'D']
for plan in plans:
#이동 후 좌표 구하기
for i in range(len(move_typeds)):
if plan == move_types[i]:
nx = x + dx[i]
ny = y + dy[i]
# 공간을 벗어나느 경우 무시
if nx < 1 or ny < 1 or nx > n or ny > n:
continue
# 이동 수행
x, y = nx, ny
print(x, y)
# 현재 나이트의 위치 입력받기
input_data = input()
row = int(input_data[1])
column = int(ord(input_data[0])) - int(ord('a')) + 1
# 나이트가 이동할 수 있는 8가지 방향 정의
steps = [(-2, -1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1)]
result = 0
for step in steps:
next_row = row + step[0]
next_column = column + step[1]
# 해당 위치로 이동이 가능하다면 카운트 다운
# 체스판과 같은 8 × 8 좌표 평면으로 표현(범위)
if next_row >= 1 and next_row <= 8 and next_column >= 1 and next_column <= 8:
result += 1
print(result)
# N, M을 공백으로 구분하여 입력받기
n, m = map(int, input().split())
# 방문한 위치를 저장하기 위한 맵을 생성하여 0으로 초기화
d = [[0]*m for_in range(n)]
# 현재 캐릭터의 x좌표, y좌표, 방향을 입력받기
x, y, direction = map(int, input().split())
d[x][y] = 1 # 현재 좌표 방문 처리
# 전체 맵 정보를 입력받기
array = []
for i in range(n):
array.append(list(map(int, input().split())))
# 북, 동, 남, 서 방향 정의
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
# 왼쪽으로 회전
def turn_left():
global direction
direction -= 1
if direction == -1:
direction = 3
# 시뮬레이션 시작
count = 1
turn_time = 0
while True:
# 왼쪽으로 회전
turn_left()
nx = x + dx[direction]
ny = y + dy[direction]
# 회전한 이후 정면에 가보지 않은 칸이 존재하는 경우 이동
if d[nx][ny] == 0 and array[nx][ny] == 0:
d[nx][ny] = 1
x = nx
y = ny
count += 1
turn_time = 0
continue
# 회전한 이후 정면에 가보지 않은 칸이 없거나 바다인 경우
else:
turn_time += 1
# 네 방향 모두 갈 수 없는 경우
if turn_time == 4:
nx = x - dx[direction]
ny = y - dy[direction]
# 뒤로 갈 수 있다면 이동하기
if array[nx][ny] == 0:
x = nx
y = ny
# 뒤가 바다로 막혀있는 경우
else:
break
turn_time = 0
# 정답 출력
print(count)
def souliton(answer):
answer = []
supo = [[1, 2, 3, 4, 5], [2, 1, 2, 3, 2, 4, 2, 5], [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]]
right = [0, 0, 0]
for i in range(len(supo)):
for j in range(len(answers)):
n = len(supo[i])
if answers[j] == supo[i][j%n]
right[i] += 1
for idx, score in enumerate(right):
if score == max(right):
answer.append(idx+1)
return answer
enumerate() 함수
인덱스(index)와 원소를 동시에 접근하면서 루프를 돌림
>>> for entry in enumerate(['A', 'B', 'C']):
... print(entry)
...
(0, 'A')
(1, 'B')
(2, 'C')
다른풀이
def solution(answers):
answer = []
grade = [0]*3
first = [1,2,3,4,5] #5개<-%5
second = [2, 1, 2, 3, 2, 4, 2, 5] #8개<-%8
third = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] #10개<-%10
for idx in range(0, len(answers)):
if answers[idx] == first[idx%5]:
grade[0] += 1
if answers[idx] == second[idx%8]:
grade[1] += 1
if answers[idx] == third[idx%10]:
grade[2] += 1
max_grade = max(grade)
for idx in range(0, 3):
if grade[idx] == max_grade:
answer.append(idx+1)
return answer