티스토리 뷰

알고리즘

[프로그래머스] hash 문제 전화번호 목록

도라지보다더덕 2020. 2. 22. 21:48

프로그래머스 문제 풀러가기

 

 

프로그래머스

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

programmers.co.kr

내 풀이:

from itertools import combinations as combi

def solution(phoneBook):
    answer = True
    for (a,b) in combi( sorted(phoneBook, key= len),2):
        if a == b[:len(a)]:
            answer = False

    return answer

테스트 케이스는 통과했지만 효율성 측면에서 통과하지 못했습니다. 문제 풀이 과정에서

from itertools import combinations
permutations
를 알게 됐는데 조합 사용 시 활용하기 편리할 것 같네요

 

참고 풀이:

from itertools import combinations as combi
def solution(phoneBook):
    phoneBook = sorted(phoneBook)

    for p1, p2 in combi(phoneBook,2):
        if p2.startswith(p1):
            return False
    return True

참고 풀이에서는 combinations를 안쓰고 zip을 썼습니다. zip을 쓸 경우 테스트 통과가 안돼서 combinations와 startswith를 썼습니다. 그렇게 하니 효율성 테스트 통과가 가능하네요. 왜 그런지는 모르겠습니다.

 

정리

  1. from itertool import combinations, permutations
    하나의 리스트에서 순서없는 조합, 순서있는 조합을 구할 때 사용합니다.
    사용방법 combinations(list,원소 개수 (ex =2))
  2. startswith
    str.startswith(str,begin, end)
    문자열에 해당 문자열이 있는 지 확인하는 메소드로 시작위치(begin), 끝 위치(end)를 넣어 검색할 문자열(str)을 검색할 수 있습니다.
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함