# Python program to find happiness by checking participation of elements into sets

PythonServer Side ProgrammingProgramming

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
• 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
Updated on 12-Oct-2021 07:56:58