|
| 1 | +""" |
| 2 | +Task: |
| 3 | +Given an array of integers citations where citations[i] is the number of |
| 4 | +citations a researcher received for their ith paper, return compute the |
| 5 | +researcher's h-index. |
| 6 | +
|
| 7 | +According to the definition of h-index on Wikipedia: A scientist has an |
| 8 | +index h if h of their n papers have at least h citations each, and the other |
| 9 | +n - h papers have no more than h citations each. |
| 10 | +
|
| 11 | +If there are several possible values for h, the maximum one is taken as the |
| 12 | +h-index. |
| 13 | +
|
| 14 | +H-Index link: https://en.wikipedia.org/wiki/H-index |
| 15 | +
|
| 16 | +Implementation notes: |
| 17 | +Use sorting of array |
| 18 | +
|
| 19 | +Leetcode link: https://leetcode.com/problems/h-index/description/ |
| 20 | +
|
| 21 | +n = len(citations) |
| 22 | +Runtime Complexity: O(n * log(n)) |
| 23 | +Space Complexity: O(1) |
| 24 | +
|
| 25 | +""" |
| 26 | + |
| 27 | + |
| 28 | +def h_index(citations: list[int]) -> int: |
| 29 | + """ |
| 30 | + Return H-index of citations |
| 31 | +
|
| 32 | + >>> h_index([3, 0, 6, 1, 5]) |
| 33 | + 3 |
| 34 | + >>> h_index([1, 3, 1]) |
| 35 | + 1 |
| 36 | + >>> h_index([1, 2, 3]) |
| 37 | + 2 |
| 38 | + >>> h_index('test') |
| 39 | + Traceback (most recent call last): |
| 40 | + ... |
| 41 | + ValueError: The citations should be a list of non negative integers. |
| 42 | + >>> h_index([1,2,'3']) |
| 43 | + Traceback (most recent call last): |
| 44 | + ... |
| 45 | + ValueError: The citations should be a list of non negative integers. |
| 46 | + >>> h_index([1,2,-3]) |
| 47 | + Traceback (most recent call last): |
| 48 | + ... |
| 49 | + ValueError: The citations should be a list of non negative integers. |
| 50 | + """ |
| 51 | + |
| 52 | + # validate: |
| 53 | + if not isinstance(citations, list) or not all( |
| 54 | + isinstance(item, int) and item >= 0 for item in citations |
| 55 | + ): |
| 56 | + raise ValueError("The citations should be a list of non negative integers.") |
| 57 | + |
| 58 | + citations.sort() |
| 59 | + len_citations = len(citations) |
| 60 | + |
| 61 | + for i in range(len_citations): |
| 62 | + if citations[len_citations - 1 - i] <= i: |
| 63 | + return i |
| 64 | + |
| 65 | + return len_citations |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + import doctest |
| 70 | + |
| 71 | + doctest.testmod() |
0 commit comments