Program to check if the given list has Pythagorean Triplets or not in Python


Suppose we have a list of numbers called nums, we have to check whether there exist three numbers a, b, and c such that a^2 + b^2 = c^2.

So, if the input is like [10, 2, 8, 5, 6], then the output will be True, as 8^2 + 6^2 = 64+36 = 100 = 10^2.

To solve this, we will follow these steps −

  • tmp := list of square of all numbers in nums in descending order
  • for each index i and corresponding number n in tmp, do
    • base := n
    • left := i+1, right := size of tmp -1
    • while left <= right, do
      • t := join two lists tmp[left] and tmp[right]
      • if t is same as base, then
        • return True
      • otherwise when t > base, then
        • left := left + 1
      • otherwise,
        • right := right - 1
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      tmp = sorted([n*n for n in nums], reverse = True)
      for i, n in enumerate(tmp):
         base = n
         left = i+1; right = len(tmp)-1
         while left <= right:
            t = tmp[left]+tmp[right]
            if t == base:
               return True
            elif t > base:
               left += 1
            else:
               right -= 1
      return False
ob = Solution()
print(ob.solve([10, 2, 8, 5, 6]))

Input

[10, 2, 8, 5, 6]

Output

True

Updated on: 07-Oct-2020

881 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements