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

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: 2020-10-07T13:24:11+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements