
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Elements greater than the previous and next element in an Array in C++
- Python Program to find the Next Nearest element in a Matrix
- Python program to count the elements in a list until an element is a Tuple?
- Program to count index pairs for which array elements are same in Python
- Count distinct elements in an array in Python
- JAVA Program to Replace Each Element of Array with its Next Element
- Python Program to Count Inversions in an array
- Swift Program to Count the elements of an Array
- Program to find smallest index for which array element is also same as index in Python
- Count frequencies of all elements in array in Python\n
- Next Greater Element in Circular Array in JavaScript
- Program to count nice pairs in an array in Python
- Python Program to find the largest element in an array
- Program to count number of paths whose sum is k in python
- Count of element in an array whose set bits are in a multiple of K

Advertisements