문자열 my_string이 매개변수로 주어집니다. my_string에서 중복된 문자를 제거하고 하나의 문자만 남긴 문자열을 return하도록 solution 함수를 완성해주세요.
| 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):
dic = {}
for i in my_string:
# if i in dic:
# dic[i] = dic[i] + 1
# else:
dic[i] = 1
return ''.join(dic.keys())
| my_string | result |
|---|---|
| "people" | "peol" |
dic은 다음과 같이 나타난다.{'p': 1, 'e': 1, 'o': 1, 'l': 1}{'p': 2, 'e': 2, 'o': 1, 'l': 1}def solution(my_string):
return ''.join(dict.fromkeys(my_string))
dict.fromkeys(seq, value)
딕셔너리를 생성할 때 편리하게 사용할 수 있는 메소드. seq 옵션 값에 문자열을 입력할 수도 있다.
- seq: 생성하려는 dictionary의 키(key)의 목록
- value: 생성하려는 dictionary의 값(value)
- 사용 예시
seq = ('name', 'age', 'sex') dict_1 = dict.fromkeys(seq) print(dict_1) dict_2 = dict.fromkeys(seq, 10) print(dict_2) result {'age':None, 'name':None, 'sex':None} {'age':10, 'name':10, 'sex':10}
def solution(my_string):
answer = ''
for i in my_string:
if i not in answer:
answer+=i
return answer