DDC-8: Test for Pythagorean triplets
A data challenge a day helps you master machine learning
About these daily data challenges
Each post is an exercise that helps you learn about data in Python.
Try to solve the exercise before checking my solution at the bottom of the post 🤓
You can share your solution or visualization in the comments!
Today’s challenge
A Pythagorean triplet is a set of three numbers for which the following is true:
That comes from the length of the hypotenuse of a right-triangle, but you don’t need to worry about geometry here. Instead, your goal is to write a Python function that gets three numbers from the user (using the input()
function) and then tests whether the squared largest of the numbers equals the sum of squares of the other two.
The screenshot below shows the function mid-run, awaiting the third input.
And here’s the final result for this run:
.
.
.
.
Scroll down for the solution…
.
.
.
.
.
.
.
.
keep scrolling!
.
.
.
.
def isPythagoreanTriplet():
# get three inputs
a = float(input('One number: '))
b = float(input('A second number: '))
c = float(input('A third number: '))
# sort them to find the largest
sorted = [a,b,c]
sorted.sort()
# test for a triplet and print the results
if sorted[-1]**2 == sorted[0]**2 + sorted[1]**2:
print('This is a Pythagorean triplet :)')
else:
print('This is not a Pythagorean triplet :(')
# run the function!
isPythagoreanTriplet()