Check Value and Frequency of Elements in Python



Suppose we have a list of numbers called nums, we have to check whether there is an element whose frequency is same as its value.

So, if the input is like nums = [2,5,7,5,3,5,3,5,9,9,5], then the output will be True, because 5 appears 5 times.

To solve this, we will follow these steps −

  • nums_c := a list containing frequencies of each elements present in nums

  • for each value i and frequency j in nums_c, do

    • if i is same as j, then

      • return True

  • return False

Example

Let us see the following implementation to get better understanding

from collections import Counter
def solve(nums):
   nums_c = Counter(nums)
   for i, j in nums_c.items():
      if i == j:
         return True
   return False

nums = [2,5,7,5,3,5,3,5,9,9,5]
print(solve(nums))

Input

[2,5,7,5,3,5,3,5,9,9,5]

Output

True
Updated on: 2021-10-11T07:12:26+05:30

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements