
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Pythagorean Triplets 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
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
Advertisements