
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if i+1 in s, then
- count := count + 1
- if i+1 in s, then
- return count
Let us see the following implementation to get better understanding −
Example
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
Advertisements