- Trending Categories
- 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 check whether elements frequencies are even or not in Python
Suppose we have a list of elements called nums, we have to check whether all numbers appear even times or not. We have to solve it using constant space.
So, if the input is like nums = [8, 9, 9, 8, 5, 5], then the output will be True, because all number have occurred twice.
To solve this, we will follow these steps −
if size of nums is odd, then
return False
sort the list nums
for i in range 1 to size of nums, do
if nums[i] is same as nums[i - 1], then
nums[i] := 0,
nums[i - 1] := 0
return true when sum of all elements present in nums is same as 0 otherwise false
Example
Let us see the following implementation to get better understanding
def solve(nums): if len(nums) & 1: return False nums.sort() for i in range(1, len(nums)): if nums[i] == nums[i - 1]: nums[i] = nums[i - 1] = 0 return sum(nums) == 0 nums = [8, 9, 9, 8, 5, 5] print(solve(nums))
Input
[8, 9, 9, 8, 5, 5]
Output
True
Advertisements