Problem
You are given a word S composed only of lowercase letters. For each letter of the alphabet, output the position of its first occurrence in the word if it is present; if it is not present, output -1.
Input
The first line contains the word S. The length of the word does not exceed 100, and it consists only of lowercase letters.
baekjoon
Output
For each letter of the alphabet, output the position of its first occurrence, separated by spaces (e.g., the position of 'a', the position of 'b', ..., the position of 'z'). If a letter is not present in the word, output -1. The first character of the word is at position 0, and the second character is at position 1.
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
My first solution
Read the word S from the first line and create an empty str called result. Use a for loop with the Unicode values of lowercase letters to find the index using the find method in S and add the result to result. Finally, use the join method to insert spaces between the characters.
import sys
S = sys.stdin.readline().strip()
result = ""
for i in range(ord('a'), ord('z') + 1):
temp = S.find(chr(i))
result += str(temp)
print(' '.join(result).strip())
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
My final solution
I simply thought I could store the indices as strings because the find method returns an index. However, since the find method returns "-1" when the substring is not found, I need to store the results in a list instead. This way, the join method will work as intended.
import sys
S = sys.stdin.readline().strip()
result = []
for i in range(ord('a'), ord('z') + 1):
temp = S.find(chr(i))
result.append(str(temp))
print(' '.join(result))
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
'Inactive Board' 카테고리의 다른 글
[Python] Linked List: What is the Node include? (4) | 2024.11.11 |
---|---|
[Python] 백준 10809번: find()는 인덱스만 반환하는가? (0) | 2024.11.09 |
[Python] 배열: 인덱스의 시작은 0인가, 1인가? (8) | 2024.11.05 |
[Python] Arrays: Is the starting index 0 or 1? (3) | 2024.11.04 |
[Python] 백준 3052번: "{}"은 집합? 딕셔너리? (0) | 2024.11.02 |