In: Computer Science
Q6: (Sides of a Right Triangle) Write a function that reads three nonzero integers and determines whether they are the sides of a right-angled triangle. The function should take three integer arguments and return 1 (true) if the arguments comprise a right-angled triangle, and 0 (false) otherwise. Use this function in a program that inputs a series of sets of integers. Hint: a^2+b^2=C^2
Code win python
def isright(list):
list.sort() # sorting to find the largest element
a = list[0]
b = list[1]
c = list[2]
if a < 0 or b < 0 or c < 0: # checking if any element is less than zero
return 0
else:
if (a * a + b * b) == c * c: # checking a^2 + b^2 = c^2
return 1
else:
return 0
if __name__ == '__main__':
n = int(input("Enter the number of series of elements:"))
data = []
for i in range(n):
print("Sides for triangle {i}:".format(i=i+1))
a = int(input())
b = int(input())
c = int(input())
list = [a, b, c]
data.append(list) # storing data in list like [[1,2,3],[2,4,5]]
for sides in data:
if isright(sides):
print("{a},{b},{c} is a right angled triangle".format(a=sides[0], b=sides[1], c=sides[2]))
else:
print("{a},{b},{c} is not a right angled triangle".format(a=sides[0], b=sides[1], c=sides[2]))
Output:
Explaination:
Initially take the number of series of elements which the user wants to input which is stored in n. For each series we form a list/array of elements which we store in a list so the data variable has something like this:
data = [[1,2,3], [3,4,5], [5,7,9] and so on]
for each array in data i.e for [1, 2, 3] (initial case according to the example)
then in the function isright we first sort the list of elements i.e if we get say list as [10, 6,9] we need to find the largest of three element which will be our c then we checik the equation a^2 + b^2 = c^2 if it is true or not then return 0 or 1 accordingly.
Screenshot of code for getting the spaces in python: