이번에도 딕셔너리를 이용해서 푸는 문제이다. 구글링해보면 대부분 처음부터 2개의 딕셔너리를 만들어서 풀었던데, 나는 values로 key를 찾는 방법으로 많이 쓰이는 방법을 이용하였다.
import sys
N, M = map(int, input().split())
pokemon = {}
for i in range(N):
pokemon[sys.stdin.readline().strip()] = i+1
reversedPokemon = dict(map(reversed, pokemon.items()))
for _ in range(M):
find = sys.stdin.readline().strip()
if pokemon.get(find) != None: # 입력값이 알파벳이다.
print(pokemon[find])
else:
print(reversedPokemon[int(find)])
find.isdigit() == False
find.isalpha() == True
import sys
N, M = map(int, input().split())
pokemon = {}
for i in range(N):
pokemon[sys.stdin.readline().strip()] = i+1
reversedPokemon = list(pokemon.keys())
for _ in range(M):
find = sys.stdin.readline().strip()
if pokemon.get(find) != None: # 입력값이 알파벳이다.
print(pokemon[find])
else:
print(reversedPokemon[int(find)-1])
print(pokemon.items())
하면 아래처럼 출력된다.
dict_items([('Bulbasaur', 1), ('Ivysaur', 2), ('Venusaur', 3), ... ('Raichu', 26)])
a = list(pokemon.items())
print(a[0][0])
print(a[0][1])
print(a[1][0])
print(a[1][1])
하면 아래와 같이 출력된다.
Bulbasaur
1
Ivysaur
2

역시 reversed를 사용해서 연산을 한 번 더 하는 것보다 바로 리스트를 만들어버리는 게 더 빠르군