Skip to content

Commit

Permalink
Most common element (#29)
Browse files Browse the repository at this point in the history
This is my suggestion for an implementation of the function most_common_element with pure Python commands, not using numpy. :-)
A test was provided.
  • Loading branch information
gudlot authored Aug 29, 2024
1 parent 53e3b93 commit 3f210e5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
28 changes: 25 additions & 3 deletions src/listwiz/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,28 @@ def longest_decreasing_streak(l):
raise NotImplementedError


def most_common_element(l):
# Find the most common element in the list
raise NotImplementedError
def most_common_element(ll):
"""Find the most common element in a list.
Parameters
----------
ll : list
Returns
-------
most common element
"""

if not isinstance(ll, list):
raise ValueError("Input must be a list")

counting ={}
for i in ll:
if i in counting:
counting[i] += 1
else:
counting[i] = 1

# Find the key with the maximum value
most_common = max(counting, key=counting.get)
return most_common
7 changes: 5 additions & 2 deletions tests/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ def test_longest_decreasing_streak():
raise AssertionError("This test is missing.")


@pytest.mark.skip(reason="Test is not implemented yet")

def test_most_common_element():
raise AssertionError("This test is missing.")
ll = [1, 2, 3, 4, 1, 1, 2, 3, 3, 3, 3, 3]
res = lwi.most_common_element(ll)
assert res == 3


0 comments on commit 3f210e5

Please sign in to comment.