Program to check same value and frequency element is there or not in Python

PythonServer Side ProgrammingProgramming

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
raja
Published on 11-Oct-2021 07:12:26
Advertisements