Count Elements x and x+1 Present in List in Python
Suppose we have a list of numbers called nums, we have to find the number of elements x
there are such that x + 1 exists as well.
So, if the input is like [2, 3, 3, 4, 8], then the output will be 3
To solve this, we will follow these steps −
- s := make a set by inserting elements present in nums
- count := 0
- for each i in nums, do
- return count
Let us see the following implementation to get better understanding −
Example
Live Demo
class Solution:
def solve(self, nums):
s = set(nums)
count = 0
for i in nums:
if i+1 in s:
count += 1
return count
ob = Solution()
nums = [2, 3, 3, 4, 8]
print(ob.solve(nums))
Input
[2, 3, 3, 4, 8]
Output
3
Related Articles
- Find all elements count in list in Python
- Difference between x++ and x= x+1 in Java programming
- If \( x+\frac{1}{x}=3 \), calculate \( x^{2}+\frac{1}{x^{2}}, x^{3}+\frac{1}{x^{3}} \) and \( x^{4}+\frac{1}{x^{4}} \).
- If \( x^{4}+\frac{1}{x^{4}}=194 \), find \( x^{3}+\frac{1}{x^{3}}, x^{2}+\frac{1}{x^{2}} \) and \( x+\frac{1}{x} \)
- Count elements in Array having strictly smaller and strictly greater elements present
- If $x^{2}+\frac{1}{x^{2}}=18$, find the values of $x+\frac{1}{x}$ and $x-\frac{1}{x}$.
- Count elements such that there are exactly X elements with values greater than or equal to X in C++
- If the points $(x+1,\ 2),\ (1,\ x+2)$ and $( \frac{1}{x+1},\ \frac{2}{x+1})$ are collinear, then find $x$.
- Program to count number of ways we can fill 3 x n box with 2 x 1 dominos in Python
- If $x - \frac{1}{x} = 3$, find the values of $x^2 + \frac{1}{x^2}$ and $x^4 + \frac{1}{x^4}$.
- Check if elements of Linked List are present in pair in Python
- Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x).
- Simplify the following:$\frac{x^{-1}+y^{-1}}{x^{-1}}+\frac{x^{-1}-y^{-1}}{x^{-1}}$
- Check whether the following are quadratic equations:(i) \( (x+1)^{2}=2(x-3) \)(ii) \( x^{2}-2 x=(-2)(3-x) \)(iii) \( (x-2)(x+1)=(x-1)(x+3) \)(iv) \( (x-3)(2 x+1)=x(x+5) \)(v) \( (2 x-1)(x-3)=(x+5)(x-1) \)(vi) \( x^{2}+3 x+1=(x-2)^{2} \)(vii) \( (x+2)^{3}=2 x\left(x^{2}-1\right) \)(viii) \( x^{3}-4 x^{2}-x+1=(x-2)^{3} \)
- If \( x+\frac{1}{x}=\sqrt{5} \), find the values of \( x^{2}+ \frac{1}{x^{2}} \) and \( x^{4}+\frac{1}{x^{4}} \).
Kickstart Your Career
Get certified by completing the course
Get Started