728x90
def solution(citations):
if min(citations) >= len(citations):
return len(citations)
answer = []
h_list = list(range(min(citations), max(citations)+1))
for h in h_list:
more = [c for c in citations if c >= h]
less = [c for c in citations if c <= h]
# print(more, less)
if len(more) >= h and len(less) <= h:
# print(more, less)
answer.append(h)
# print(answer)
else:
# print(answer)
if len(answer) == 0:
return 0
else:
return max(answer)
테스트 케이스 [22, 42] 인 경우
리스트 최대 개수가 2인데 h-index의 최소값은 22이기 때문에 for 문 안의 if 문에서 조건을 찾을 수 없다.
다른 풀이
def solution(citations):
citations = sorted(citations)
l = len(citations)
for i in range(l):
if citations[i] >= l-i:
return l-i
return 0
pythonic한 풀이
def solution(citations):
citations.sort(reverse=True)
answer = max(map(min, enumerate(citations, start=1)))
return answer
sort로 정렬해서 가장 큰값부터 작은값으로 정렬한후, enumerate로 (index, value)형태로 묶는다. 그리고 최댓값(start = 1)부터 각 value에 대해 최솟값 value의 값을 min으로 추출하고, 이 추출된 값은 enumerate가 끝나는 citations 리스트의 크기에 해당하는 갯수가 나온다. 이들을 map으로 묶으면, 한 value의 입장에서 보는 최솟값 value의 집합이 나온다. 즉 h값들의 집합이나온다. h값중 최대값을 max로 뽑아서 출력하면 된다.
라고 하는데
map(min, enumerate(citations, start=1))
[3, 0, 6, 1, 5]의 경우
descending order 로 한 후
이 코드를 출력해보면
[1, 2, 3, 1, 0]
이 리스트를 반환한다
enumerate에서 나온 idx, value로 된 tuple 중 최소값을 리스트로 만들어서 반환하는 것이다
[6,5,3,1,0]을 enumerate로 넣으면(start=1)
(1, 6) -> 1
(2, 5) -> 2
(3, 3) -> 3
(4, 1) -> 1
(5, 0) -> 0
728x90
'Algorithm' 카테고리의 다른 글
[프로그래머스] 타겟 넘버 (BFS/DFS) 파이썬 (0) | 2021.03.15 |
---|---|
[프로그래머스] 카펫 파이썬 (0) | 2021.03.12 |
[프로그래머스] 전화번호 목록 파이썬 Hash (0) | 2021.03.11 |
[프로그래머스] 가장 큰 수 파이썬 (0) | 2021.03.11 |
[프로그래머스] 소수 찾기 파이썬 (0) | 2021.03.10 |
댓글