Count Duplicates in a Python String

To count duplicates in a Python string:

from collections import Counter

my_string = "abcaaba"

my_dict = dict(Counter(my_string))
duplicates = {k: v for k, v in my_dict.items() if v > 1}

print(duplicates)

The result:

{'a': 4, 'b': 2}

Function to Count Duplicates in a String

Here is a function to count duplicates in a Python string:

from collections import Counter


def count_duplicates(my_string: str) -> dict:
"""
Count the number of duplicates in a string.
:param my_string: The input string that contains the duplicates.
:return: a dictionary that contains the number of duplicates in a string.
"
""
my_dict = dict(Counter(my_string))
duplicates = {k: v for k, v in my_dict.items() if v > 1}
return duplicates


example_string = "abcaaba"
print(count_duplicates(example_string))

The result:

{'a': 4, 'b': 2}

Test the Function

To test the above function using Pytest:

import pytest

# Assuming the count_duplicates function is stored under app.string_operations
from app.string_operations import count_duplicates


@pytest.mark.parametrize(
"my_string, expected_output",
[
("abcaaba", {"a": 4, "b": 2}),
("aabbcc", {"a": 2, "b": 2, "c": 2}),
("abc aa ba", {"a": 4, "b": 2, " ": 2}),
("a", {}),
("abc", {}),
("", {}),
],
)
def test_count_duplicates(my_string, expected_output):
"""
Test the count_duplicates function across different strings.

:param my_string: The input string to be tested
:param expected_output: The expected number of duplicates in the string
"
""
assert count_duplicates(my_string) == expected_output

The result:

============================= test session starts =============================
collecting ... collected 6 items

test_string_operations.py::test_count_duplicates[abcaaba-expected_output0] PASSED [ '16%']
test_string_operations.py::test_count_duplicates[aabbcc-expected_output1] PASSED [ '33%']
test_string_operations.py::test_count_duplicates[abc aa ba-expected_output2] PASSED [ '50%']
test_string_operations.py::test_count_duplicates[a-expected_output3] PASSED [ '66%']
test_string_operations.py::test_count_duplicates[abc-expected_output4] PASSED [ '83%']
test_string_operations.py::test_count_duplicates[-expected_output5] PASSED ['100%']

============================== 6 passed in '0.02s' ==============================

Additional Resources

Leave a Comment