[code_kata] 공통된 시작 단어 반환
*문제 😀
strs은 단어가 담긴 배열입니다.
공통된 시작 단어(prefix)를 반환해주세요.
예를 들어😉
strs = ['start', 'stair', 'step']
return은 'st'
strs = ['start', 'wework', 'today']
return은 ''
풀이 😀
def get_prefix(strs):
if len(strs) == 0:
return ''
empty = ''
strs = sorted(strs)
for i in strs[0]:
if strs[-1].startswith(empty+i):
empty += i
else:
break
return empty
strs = ['start', 'wework', 'today']
get_prefix(strs)
시각화 툴을 이용한 이해(pythontutor.com)
def get_prefix(strs):
if len(strs) == 0:
return ''
empty = ''
strs = sorted(strs)
for i in strs[0]:
if strs[-1].startswith(empty+i):
empty += i
else:
break
return empty
strs = ['start', 'wework', 'today']
get_prefix(strs)
참고할 만한 메서드😀
startswith()🚕
사용방법
사용방법
startswith(str or tuple, 시작idx, 끝idx)
그러면 return
값은 True, False
를 매칭 유무에 따라 반환해요.
1. 일반적 사용🚗
2. 대소문자를 구분한 모습🚗
3. 튜플 사용 가능🚗
4. 리스트 사용 NO!NO!🚗
5. 시작 부분이 인자값과 일치 하지 않은 경우🚗
6. 옵션 인자(시작idx, 끝idx)를 지정한 경우🚗
위 예시에서 2~3번째 인자는 옵션 인자인만큼 end 인덱스를 굳이 안넣어줘도 True를 반환해줘요.
sorted()🚕
-
list.sort()
는 리스트 내부에서 정렬! -
however sorted()는
sort()
와 비슷하지만값을 반환!!!
한다는점! -
기존 객체의 값을 변경시키지 않고 정렬된 값을 갖고 싶은 경우에는
sorted()
를 사용함 -
list.sort()
는List
type
에 한정해서 작동해요. 그러나sorted()
는iterable
한 자료형list, dict, set, str, bytes, tuple, range
모두에 적용 가능하다는 사실😲😃
>>> sorted({3: 'D', 1: 'B', 2: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
추가적으로 더 있지만 이정도로 할게요.
Author And Source
이 문제에 관하여([code_kata] 공통된 시작 단어 반환), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hyeseong-dev/codekata저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)