프로그래머스 문자열 다루기
https://school.programmers.co.kr/learn/courses/30/lessons/12918
내 정답코드
def solution(s):
if len(s) == 4 or len(s) == 6:
if s.isdigit():
return True
else:
return False
else:
return False
조건에 맞게 4혹은 6일때 isdigit()
로 숫자만 있는지 검사해서 결과값을 반환한다
지현님 코드
def solution(s):
if len(s) == 4 or len(s) == 6:
for alpha in s:
if alpha.isalpha():
answer = False
break
else:
answer = True
else:
answer = False
return answer
보영님 코드
def solution(s):
answer = True
len_s = len(s)
if len_s == 4 or len_s == 6:
try:
int(s)
except ValueError:
answer = False
else:
answer = False
return answer
프로그래머스 문자열 내마음대로 정렬하기
https://school.programmers.co.kr/learn/courses/30/lessons/12915
내 코드
def solution(strings, n):
answer = []
for i in range(len(strings)):
strings[i] = strings[i][n] + strings[i]
strings.sort()
for i in range(len(strings)):
answer.append(strings[i][1:])
return answer
answer
리스트를 초기화시킨다
strings
의 길이만큼 반복시켜 그 값을 인덱스로 사용해 n번째 문자를 앞쪽에 하나씩 더해준다
sort()
로 정렬한다
정렬한 리스트를 answer
리스트에 추가하여 슬라이싱 하고 반환한다
Python Coroutine
def my_coroutine():
while True:
x = yield
print('Received:', x)
co = my_coroutine()
next(co)
co.send(10) # Received: 10
co.send(20) # Received: 20
co.send(30) # Received: 30
하나씩 디버깅을 해보자
my_corountine
이 실행되는 순서를 보면 next(co)
로 인해 while문이 실행이 되고 x
에 co.send(10)
으로 10을 x
에 넣고 print
가 실행되어 Received: 10
가 출력된다
이후부터는 next(co)
는 기억하기 때문에 더이상 가지 않는다
phone_book = {'John': '123-4567', 'Jane': '234-5678', 'Max': '345-6789'}
def search():
name = yield
while True:
if name in phone_book:
phone_number = phone_book[name]
else:
phone_number = "Cannot find the name in the phone book."
name = yield phone_number
# 코루틴 객체 생성
search_coroutine = search()
next(search_coroutine)
# example
result = search_coroutine.send('John')
print(result) # 123-4567
result = search_coroutine.send('Jane')
print(result) # 234-5678
result = search_coroutine.send('Sarah')
print(result) # Cannot find the name in the phone book.
이도 비슷하다
next(search_coroutine)
으로 함수에서 name = yeild
문으로 가고 while
문을 돌리고 if
로 가서 name =yeild phone_number
로 인해 while
을 빠져나오고 print
가 된다