Syntax error Program to count index pairs for which array elements are same in Python

Program to count index pairs for which array elements are same in Python



Suppose we have a list of numbers called nums. We have to find the number of pairs i < j such that nums[i] and nums[j] are same.

So, if the input is like nums = [5, 4, 5, 4, 4], then the output will be 4, as We have index pairs like (0, 2), (1, 3), (1, 4) and (3, 4).

To solve this, we will follow these steps −

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

  • count := 0

  • for each n in list of all values of c, do

    • count := count + floor of (n *(n - 1)) / 2

  • return count

Example

Let us see the following implementation to get better understanding

from collections import Counter
def solve(nums):
   c = Counter(nums)
   count = 0
   for n in c.values():
      count += n * (n - 1) // 2
   return count

nums = [5, 4, 5, 4, 4]
print(solve(nums))

Input

[5, 4, 5, 4, 4]

Output

4
Updated on: 2021-10-11T07:09:51+05:30

628 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements