Was it helpful?

Question

Program to find the product of three elements when all are unique in Python

PythonServer Side ProgrammingProgramming

Suppose we have three numbers, x, y, and z, we have to find their product, but if any two numbers are equal, they do not count.

So, if the input is like x = 5, y = 4, z = 2, then the output will be 40, as all three numbers are distinct so their product is 5 * 4 * 2 = 40

To solve this, we will follow these steps −

  • temp_set := a new set
  • remove := a new set
  • for each i in [x,y,z], do
    • if i is in temp_set, then
      • insert i into the set called remove
    • insert i in to the set temp_set
  • for each i in remove, do
    • delete i from temp_set
  • multiplied := 1
  • for each i in temp_set, do
    • multiplied := multiplied * i
  • return multiplied

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, x, y, z):
      temp_set = set()
      remove = set()
      for i in [x, y, z]:
         if i in temp_set:
            remove.add(i)
         temp_set.add(i)
      for i in remove:
         temp_set.remove(i)
      multiplied = 1
      for i in temp_set:
         multiplied *= i
      return multiplied
ob = Solution()
print(ob.solve(5, 4, 2))

Input

5, 4, 2

Output

40
raja
Published on 05-Oct-2020 11:08:58
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top