- 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 elements whose next element also in the array in Python
Suppose we have a list of numbers say nums, we have to find the number of elements x in the array, such that x + 1 also exists in the array.
So, if the input is like nums = [4, 2, 3, 3, 7, 9], then the output will be 3, because 2+1 = 3 is present, 3+1 = 4 is present and another 3 is present so total 3.
To solve this, we will follow these steps −
answer := 0
c := a list containing frequencies of each elements present in nums
dlist := a list from list of all keys of c
for each i in dlist, do
if c[i + 1] > 0, then
answer := answer + c[i]
return answer
Example
Let us see the following implementation to get better understanding
from collections import Counter def solve(nums): answer = 0 c = Counter(nums) dlist = list(c.keys()) for i in dlist: if c[i + 1] > 0: answer += c[i] return answer nums = [4, 2, 3, 3, 7, 9] print(solve(nums))
Input
[4, 2, 3, 3, 7, 9]
Output
3
Advertisements
To Continue Learning Please Login
Login with Google