from string import ascii_lowercase
def solve(S):
List = list(S)
result = []
for i in ascii_lowercase:
if i in List:
result.append(List.index(i))
else:
result.append(-1)
print(' '.join(map(str, result)))
S = input()
solve(S)
알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.
첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.
각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다.
만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출력한다. 단어의 첫 번째 글자는 0번째 위치이고, 두 번째 글자는 1번째 위치이다.
baekjoon
1 0 -1 -1 2 -1 -1 -1 -1 4 3 -1 -1 7 5 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
의 문풀이다.
여기서 새로 알게된 표현은
from string import ascii_lowercase
for i in ascii_lowercase:
라는 툴을 이용해 a-z까지의 범위를 출력하는 것이다.
또한 위 식을 풀어 쓰면
from string import ascii_lowercase
def solve(S):
List = list(S)
result = []
for i in ascii_lowercase:
if i in List:
result.append(List.index(i))
else:
result.append(-1)
for i in range(len(result)):
print(result[i], end = ' ')
S = input()
solve(S)
로 쓸 수 있고,
for i in range(len(result)):
print(result[i], end = ' ')
#라는 코드를
print(' '.join(map(str, result))
로 줄일 수 있다는 것이다.
이때, map()을 사용한 이유는 . join()이 문자열을 포함한
list에 사용되는 내장함수이기 때문이다.