How to count the triangles that can be formed using three different elements of a list in Python

1 Answer

0 votes
def GetNumberOfTriangles(arr):
    size = len(arr) 
    count = 0
     
    for i in range(size):
        for j in range(i + 1, size):
            for k in range(j + 1, size):
                # triangle = sum of two sides > value of the third side
                if (arr[i] + arr[j] > arr[k] and
                    arr[i] + arr[k] > arr[j] and
                    arr[k] + arr[j] > arr[i]):
                    print(arr[i], arr[j], arr[k])
                    count += 1
    return count
 

lst = [ 2, 3, 4, 5, 6, 7 ]

print(GetNumberOfTriangles(lst))



'''
run:

2 3 4
2 4 5
2 5 6
2 6 7
3 4 5
3 4 6
3 5 6
3 5 7
3 6 7
4 5 6
4 5 7
4 6 7
5 6 7
13

'''

 



answered Sep 12, 2022 by avibootz
...