A number and its triple in Python


Suppose we have a list of numbers called nums, we have to check whether there are two numbers such that one is a triple of another or not.

So, if the input is like nums = [2, 3, 10, 7, 9], then the output will be True, as 9 is the triple of 3

To solve this, we will follow these steps −

  • i := 0

  • sort the list n

  • j := 1

  • while j < size of n, do

    • if 3*n[i] is same as n[j], then

      • return True

    • if 3*n[i] > n[j], then

      • j := j + 1

    • otherwise,

      • i := i + 1

  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      i = 0
      n.sort()
      j = 1
      while (j < len(n)):
         if (3*n[i] == n[j]):
            return True
         if (3*n[i] > n[j]):
            j += 1
         else:
            i += 1
      return False
ob = Solution()
print(ob.solve([2, 3, 10, 7, 9]))

Input

[2, 3, 10, 7, 9]

Output

True

Updated on: 02-Sep-2020

444 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements