
- 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
Python program to find happiness by checking participation of elements into sets
Suppose we have an array nums with n different integers. We also have two disjoint sets A and B. We have one happiness parameter which is set to 0 initially. We go through each integer i in nums. If i is in A then add happiness by 1 and if i is in B decrease it by 1. We have to finally find the final happiness value.
So, if the input is like nums = [1,2,5,8,6,3] A = {5,8,9,7,3} B = {2,4,12,15}, then the output will be 2 because 5, 8, 3 are in A so happiness is 3 now, but 2 is in B so decrease it by 1 then happiness is 2.
To solve this, we will follow these steps −
- happiness := 0
- for each i in nums, do
- if i is in A, then
- happiness := happiness + 1
- otherwise when i is in B, then
- happiness := happiness - 1
- if i is in A, then
- return happiness
Example
Let us see the following implementation to get better understanding
def solve(nums, A, B): happiness = 0 for i in nums: if i in A: happiness += 1 elif i in B: happiness -= 1 return happiness nums = [1,2,5,8,6,3] A = {5,8,9,7,3} B = {2,4,12,15} print(solve(nums, A, B))
Input
[1,2,5,8,6,3], {5,8,9,7,3}, {2,4,12,15}
Output
2
- Related Articles
- Python Program to find Duplicate sets in list of sets
- Python program to find common elements in three lists using sets
- C# program to find common elements in three arrays using sets
- Program to split a set into equal sum sets where elements in first set are smaller than second in Python
- How to split a Dataset into Train sets and Test sets in Python?
- Program to find number of sets of k-non-overlapping line segments in Python
- Python Program to find out the number of sets greater than a given value
- Breaking a Set into a list of sets using Python
- Program to find maximum sum by flipping each row elements in Python
- Python program to copy all elements of one array into another array
- Program to find island count by adding blocks into grid one by one in Python
- Program to pack same consecutive elements into sublist in Python
- Python program to find sum of elements in list
- Program to find sum of unique elements in Python
- C++ code to find answers by vowel checking

Advertisements