본문 바로가기
[Programmers]

[프로그래머스 Lv.0][Python] 모음 제거

by Sir교수 2023. 1. 20.
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/120849

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

​▶문제 설명

 

▶나의 풀이

 

# 처음 풀었던 방식 
def solution(my_string):
    answer = ''
    vowel = ["a", "e" , "i", "o", "u"]
    new_string = []
    for i in my_string:
        if i not in vowel:
            new_string.append(i)
    answer = ''.join(new_string)
    return answer

# list comprehension 사용
def solution(my_string):
    vowel = ["a", "e" , "i", "o", "u"]
    return ''.join([i for i in my_string if i not in vowel])

 

▶나의 풀이 방법 설명

 

# 1. 처음 풀었던 방식
 
for i in my_string:
        if i not in vowel:
            new_string.append(i)
--> 새로운 new_string 배열에 모음이 없는 문자열들만 넣어준다. 

answer = ''.join(new_string)
--> join 함수를 이용하여 리스트에서 문자열로 바꿔준다. 


# 2. list comprehension
return ''.join([i for i in my_string if i not in vowel])
--> 이렇게 줄일 수 있다니 노력해야겠다..

 

※ 사용된 문법

list comprehension :

ex)

array = ['a', 'b', 'c', 'd', 'e']

output = [fruit for fruit in array if fruit != 'c']

# 1. [for fruit in array ] -> 파악.

# 2. for 앞에 있는 (fruit)가 어떤 형태로 변형, 사용 -> append

# 3. in {arr} 다음에 있는 {if 조건절}에 따라서 원소가 추가 되는지를 결정

728x90