- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements