#C2571. Count Duplicate Elements
Count Duplicate Elements
Count Duplicate Elements
You are given a single line input representing a Python-style list. The list may contain integers, strings, and tuples. Your task is to find the duplicate elements in the list and count the number of times each duplicate element appears. Formally, if the list is denoted as L and the count of an element x is \(c(x)\), then you should output a dictionary containing each element x for which \(c(x) > 1\) along with its count.
If the input is not a valid list or if it contains elements that cannot be used as dictionary keys (i.e. unhashable items), print Invalid input
.
Note: The list is expressed in a Python literal format. For example, a tuple is represented as (1, 2)
and a string is represented with quotes, e.g. 'a'
.
inputFormat
The input consists of a single line containing a Python-style list literal. Examples:
- [1, 2, 2, 3, 4, 4, 4, 5]
- [1, 2, 3, 4, 5]
- ['a', 'b', 'a', 'c', 'b', 'b']
- [1, 2, (1, 2), (1, 2), 2]
If the input does not represent a list, it is considered invalid.
outputFormat
If the input list is valid, print the dictionary (in Python literal format) of duplicate elements and their counts. The dictionary should only contain elements with a count greater than 1. If there are no duplicates, print {}
. If the input is invalid, print Invalid input
.
For example:
- Input: [1, 2, 2, 3, 4, 4, 4, 5] → Output: {2: 2, 4: 3}
- Input: [1, 2, 3, 4, 5] → Output: {}
- Input: ['a', 'b', 'a', 'c', 'b', 'b'] → Output: {'a': 2, 'b': 3}
- Input: [1, 2, (1, 2), (1, 2), 2] → Output: {2: 2, (1, 2): 2}
- Input: this is a string → Output: Invalid input
[1, 2, 2, 3, 4, 4, 4, 5]
{2: 2, 4: 3}