Skip to content

Commit 61cfb43

Browse files
Add h index (TheAlgorithms#8036)
1 parent 3dc143f commit 61cfb43

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

Diff for: DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,7 @@
712712
* [Gauss Easter](other/gauss_easter.py)
713713
* [Graham Scan](other/graham_scan.py)
714714
* [Greedy](other/greedy.py)
715+
* [H Index](other/h_index.py)
715716
* [Least Recently Used](other/least_recently_used.py)
716717
* [Lfu Cache](other/lfu_cache.py)
717718
* [Linear Congruential Generator](other/linear_congruential_generator.py)

Diff for: other/h_index.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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

Comments
 (0)