출처: https://school.programmers.co.kr/learn/courses/30/lessons/120888?language=python3
문제 설명
문자열 my_string이 매개변수로 주어집니다. my_string에서 중복된 문자를 제거하고 하나의 문자만 남긴 문자열을 return하도록 solution 함수를 완성해주세요.
제한사항
1 ≤ my_string ≤ 110
my_string은 대문자, 소문자, 공백으로 구성되어 있습니다.
대문자와 소문자를 구분합니다.
공백(" ")도 하나의 문자로 구분합니다.
중복된 문자 중 가장 앞에 있는 문자를 남깁니다.
입출력 예
my_string result
"people" "peol"
"We are the world" "We arthwold"
입출력 예 설명
입출력 예 #1
"people"에서 중복된 문자 "p"와 "e"을 제거한 "peol"을 return합니다.
입출력 예 #2
"We are the world"에서 중복된 문자 "e", " ", "r" 들을 제거한 "We arthwold"을 return합니다.
내가 작성한 코드문
def solution(my_string):
answer = ''
data = []
for i in my_string:
data.append(i)
print(data)
unique_dict = dict.fromkeys(data)
result_list = list(unique_dict.keys())
for i in result_list:
answer += i
return answer
처음엔 set을 썼지만 순서는 보장 안되는 중복제거 였다.
그래서 dictionary를 사용해야 한다. 키는 중복 안되기에
결과: {'A': None, 'B': None, 'C': None} 이런식으로
unique_dict 변수에 저장되고,
키들을 리스트화 한다.
result_list = list(unique_dict.keys())
그 다음에 반복문을 순회하며 answer 변수에 저장.
다른 사람의 풀이
def solution(my_string):
return ''.join(dict.fromkeys(my_string))
다 원리는 같은데 더 간결하다.
def solution(my_string):
answer = ''
for i in my_string:
if i not in answer:
answer+=i
return answer
def solution(my_string):
answer = []
for i in my_string :
if answer.count(i) == 0 :
answer.append(i)
return ''.join(answer)
def solution(my_string):
answer = ''
dic = {}
# my_string의 각 문자(m)를 순서대로 반복
for m in my_string:
# 1. 문자가 dic에 없는 경우 (즉, 처음 등장하는 경우)
if m not in dic:
dic[m] = 1 # 딕셔너리에 키(문자)를 등록하여 '봤다(Seen)'고 표시
answer += m # 결과 문자열(answer)에 해당 문자를 추가
# 2. 문자가 dic에 있는 경우 (즉, 중복되어 이미 등장했던 경우)
elif m in dic:
continue # 아무 작업 없이 다음 문자로 건너뜀 (중복 제거)
return answer