programmers.co.kr/learn/courses/30/lessons/12930
코딩테스트 연습 - 이상한 문자 만들기
문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을
programmers.co.kr
def solution(s):
s_lst = s.split(' ')
result = ''
for string in s_lst:
for i in range(len(string)):
if i % 2 == 0:
result += string[i].upper()
else:
result += string[i].lower()
result += ' '
return result[:-1]
주의해야 할 점이 있는데, split(' ')을 안 하고 split()만 한다면 공백이 여러 개일 경우 하나로 합쳐 문제가 생긴다.
def solution(s):
idx = 0
result = ''
for char in s:
if char == ' ':
result += ' '
idx = 0
else:
if idx % 2 == 0:
result += char.upper()
idx += 1
else:
result += char.lower()
idx += 1
return result
처음 코드가 좀 불만족스러워서 새로 짰다. 다행히 만족스러운 코드가 나왔다.
def solution(s):
return ' '.join(map(lambda x: ''.join([v.lower() if i%2 else v.upper() for i, v in enumerate(x)]), s.split(' ')))
map, lambda와 함께라면 한줄도 가능!
'PS > 프로그래머스' 카테고리의 다른 글
[프로그래머스-Level 1] 최대공약수와 최소공배수 ❌⭕ (0) | 2021.04.08 |
---|---|
[프로그래머스-Level 1] 키패드 누르기_파이썬 ❌⭕ (0) | 2021.04.07 |
[프로그래머스-Level 1] 시저 암호_파이썬 (0) | 2021.04.05 |
[프로그래머스-Level 1] 수박수박수박수박수박수?_파이썬 (0) | 2021.04.05 |
[프로그래머스-Level 1] 소수 찾기_파이썬 (에라토스테네스의 체) (0) | 2021.04.05 |